Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React Socket.io Store Messages
I made simple chat app with Socket.io (tutorial - github) I made a users model on Django and integrated with this app. But when i close the browser and login user account again, messages be lost. I want to store messages. How can i handle with this? -
How to implement OTP based verification before letting the user to create a new password using pyotp?
I am very new to Django rest framework. I am building APIs for my mobile application. In Forgot password module, I have the below flow 1 - Ask user to enter mobile 2 - check existence 3 - If exists - > send OTP 4 - Verify and let user create a new password. But in this case, I would like to know the way of handle the below situation. When one user requests otp and waiting for it to verify , meanwhile another user requests for OTP At this time, how to handle the both user ? I thought of 1 - creating the dictionary and save the user id as key and otp as value in views.py to verify particular user . 2 - store the otp temporarily until it verifies. Kindly let me know which is the secured way and any alternative for this kind of scenario -
DJango deployment on Apache24 not working
I am new to web frameworks and I have designed small website using DJango-3.1.7. I am trying to deploy DJango website on Apache server in Windows 10 platform but it seems something not correct or I missed out it. If anyone could help with this we be precious for me. I have configured virtual environment for this application Problem: Getting error PYTHONHOME = (not set) PYTHONPATH = (not set) error.log Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\Apache24\\bin\\httpd.exe' sys.base_prefix = 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python38' sys.base_exec_prefix = 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python38' sys.executable = 'C:\\Apache24\\bin\\httpd.exe' sys.prefix = 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python38' sys.exec_prefix = 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python38' sys.path = [ 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip', '.\\DLLs', '.\\lib', 'C:\\Apache24\\bin', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00002838 (most recent call first): <no Python frame> [Sat Jun 26 21:56:47.558067 2021] [mpm_winnt:crit] [pid 5344:tid 780] AH00419: master_main: create child process failed. Exiting. etc/hosts 127.0.0.2 stack-hack.com httpd.conf LoadFile "c:/users/hp/appdata/local/programs/python/python38/python38.dll" LoadModule wsgi_module "e:/Code-Stack/stack-hack/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win_amd64.pyd" WSGIPythonHome "e:/Code-Stack/stack-hack" WSGIPythonPath "e:/Code-Stack/stack-hack/Lib/site-packages" <VirtualHost *:80> ServerAlias www.stack-hack.com ServerName stack-hack.com ServerAdmin info@admin.com WSGIScriptAlias / "E:/Code-Stack/Stack-Hack/src/stackhack/wsgi.py" <Directory … -
How to specify dynamic url in django template for class based view using router?
path('api/', include(router.urls), name='api'), path('index/' , home, name='home'), path('about/' , about, name='about'), router.register('bankdetailapi', views.BankViewSet, basename='bankdetail' ) how i wrote urls in template href="{% url 'about' %}" href="{% url 'api' %}" href="{% url 'home' %}" i am getting following error Traceback (most recent call last): File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\rest_api\api\views.py", line 36, in home return render(request,'index.html' #,{"ifsc":ifsc} File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\defaulttags.py", line 446, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\urls\base.py", line 86, in … -
django orm sort by foreign key occurence in another table
Suppose to have something like the following tables: class Book(models.Model): title = models.CharField(max_length=200) class Purchase(models.Model): book = models.CharField(Book, db_column="book", on_delete=models.CASCADE) date = models.DateField() and wanting to retrieve a queryset of books ordered by number of purchases (i.e. occurrences of the foreign key in the other table). Book.objects.all().annotate(number_of_purchases=Count(**something**)).order_by('number_of_purchases') Is this possible? I currently have no idea what the "something" should be replaced with. -
Authenticate Public APIs with HMAC and Cloudflare?
I have a react.js website that gets data from my Django-based public API. I'm looking at using HMAC tokens to authenticate my client's requests to my backend API. How do I securely implement HMAC tokens in React that are valid with Cloudflare: https://developers.cloudflare.com/firewall/recipes/require-valid-hmac-token Cloudflare proxies all requests to my backend so I need a way of enforcing the authenticity of my client if possible. -
Using custom models.py module name with custom user account app in Django
I have a custom user account model which I use in the settings like so; AUTH_USER_MODEL = 'user_account.UserAccount' This obviously refers to user_account.models.UserAccount model class. Though, I would like to rename the models.py module to user_account_models.py, in which case django naturally complains about user_account.UserAccount not being exist. I've checked the doc, and models are stated in app.ModelName format, nothing in between to refer to where the model is "since django assumes they will always be in models.py in every app" I assume. Is there a way to make django use custom names for models.py module (or any module for that matter) for a particular app (since every app will have it's own distinctive name with the app name as prefix)? -
On going to the profile page, the 'profile_pic' has no file associated with it, value error shows up
When I log in a new user this error that no files are associated with the 'profile_pic' shows up and i've set the profile_pics value to default as well but i don't know the issue any more this is models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User,null= True , blank = True, on_delete= models.CASCADE) profile_pic = models.ImageField(default = "static/profileimages/msi.jpg", null = True, blank= True) first = models.CharField(max_length=500, null=True) last = models.CharField(max_length=500, null=True) email = models.CharField(max_length=500, null=True) mobile_number = models.IntegerField(null=True) location = models.CharField(max_length= 500, null= True) postal = models.IntegerField(null=True) def __str__(self): return self.first This is the views.py: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from .forms import CreateUserForm, ProfileForm from django.http import HttpResponse, HttpResponseRedirect from django.contrib import messages from django.contrib.auth import login, authenticate, logout from django.contrib.auth.decorators import login_required from .models import * def RegisterPage(request): if request.user.is_authenticated: return redirect('Profile') else: if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() name = form.cleaned_data.get('first_name') messages.success(request, 'Account created for ' + name) Profile.objects.create( user = user, ) return HttpResponseRedirect('/Login/') else: form = CreateUserForm() context = {'form':form} return render(request, 'register.html', context) @login_required(login_url='Login') def profile(request): profile = request.user.profile form = ProfileForm(instance=profile) if request.method == 'POST': form … -
A field already has access to the other foreign key in a table
class User(models.Model): ... class Phone(models.Model): user = models.ForeignKey(User) phone = models.TextField() class profile(models.Model): user = models.ForeignKey(User) user_phone = models.ForeignKey(Phone) Already user field in profile has access to phone, So is this design ok or bad based on a normalization view? -
Django Rest Framework error in nested create serializers
I am trying to insert info into the db with nested serializers, but I have errors dummy models class Supplier(models.Model): name = models.CharField('Nombre', max_length=250) class SupplierContacts(models.Model): supplier = models.ForeignKey( 'Supplier', related_name='contacts', on_delete=models.CASCADE ) last_name = models.CharField(max_length=50) class SupplierUsers(models.Model): supplier = models.ForeignKey( 'Supplier', related_name='users', on_delete=models.CASCADE ) last_name = models.CharField(max_length=50) dummy serializers class SupplierSerializer(serializers.ModelSerializer): users = SupplierUserSerializer() contacts = SupplierContactsSerializer(many=True) class Meta: model = Supplier fields = [ 'name', 'users', 'contacts' ] def create(self, validated_data): users_data = validated_data.pop('users') contacts_data = validated_data.pop('contacts') supplier = Supplier.objects.create(**validated_data) SupplierUsers.objects.create(supplier=supplier, **users_data) for contact in contacts_data: SupplierContacts.objects.create(supplier=supplier, **contact) return supplier In views custom create like this class ViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): queryset = Supplier.objects.all() serializer_class = SupplierSerializer def create(self, request, *args, **kwargs): # import ipdb # ipdb.set_trace() serializer = SupplierSerializer(data=request.data) if serializer.is_valid(): serializer.save() # here works saved to db return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I am doing what it says in the documentation, but I have the following error. AttributeError: Got AttributeError when attempting to get a value for field `last_name` on serializer `SupplierUserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance. Original exception text was: 'RelatedManager' object has no attribute 'last_name'. Data is saved, the problem is in … -
how to test react component without updating the db
this is my test for users registration the problem is that the test actually register the user and update the db. therefore because the user getting created at the second run the test fails (beacuse the user is already registered) I wonder is there a way which I can test this component without updating the db? I am using postgreSQL as my database and django rest as my api. for the front end I am using react and for the testing: react testing library + jest test('signup should dispatch signupAction', async () => { const middlewares = [thunk]; const mockStore = configureStore(middlewares); initialState = { authReducer: { isAuthenticatedData: false }, }; const store = mockStore(initialState); render( <Provider store={store}> <Router> <UserSignup /> </Router> </Provider> ); const nameTextbox = screen.getByPlaceholderText('Name*'); const emailTextbox = screen.getByPlaceholderText('Email*'); const passwordTextbox = screen.getByPlaceholderText('Password*'); const confirmTextbox = screen.getByPlaceholderText('Confirm Password*'); const signupButton = screen.getByRole('button', { name: 'Register' }); userEvent.type(nameTextbox, 'newtestuser'); userEvent.type(emailTextbox, 'newtestuser@gmail.com'); userEvent.type(passwordTextbox, 'testuser123'); userEvent.type(confirmTextbox, 'testuser123'); userEvent.click(signupButton); await waitFor(() => expect(store.getActions()[0].type).toBe('SIGNUP_SUCCESS')); }); user sign up component const userSignup = () => { const dispatch = useDispatch(); const isAuthenticatedData = useSelector((state) => state.authReducer.isAuthenticatedData); const [formData, setFormData] = useState({ name: '', email: '', password: '', re_password: '', }); const [accountCreated, setAccountCreated] … -
TypeError: __str__ returned non-string (type NoneType) - Django
I have an error when trying to make a data listing request: MyModel: import uuid import time from django.db import models from a.models import ModelA from b.models import ModelB def upload_location(instance, filename): filebase, extension = filename.split('.') milliseconds = int(round(time.time() * 1000)) return 'a_id__%s/%s__%s.%s' % (instance.a_id, instance.name, milliseconds, extension) class Attachment(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False) name = models.CharField(max_length=150) file = models.FileField(upload_to=upload_location) a = models.ForeignKey( ModelA, null=True, blank=False, on_delete=models.CASCADE ) b = models.ForeignKey( ModelB, null=True, blank=False, on_delete=models.CASCADE ) def __str__(self): return self.name Viewset: class AttachmentsViewSet( mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): permission_classes = [permissions.AllowAny] queryset = Attachment.objects.all() serializer_class = AttachmentSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data data['a_id'] = request.user.a_id data['name'] = str(request.data['file']) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) Serializer: class AttachmentSerializer(ModelSerializer): class Meta: model = Attachment fields = "__all__" class ASerializer(ModelSerializer): attachment = serializers.SerializerMethodField('get_attachment_model_b') class Meta: model = ModelB fields = ( 'id', 'type', 'name', 'status', 'attachment' ) def get_attachment_model_b(self, obj): attachment = Attachment.objects.filter(b_id=obj.b_id).all() return AttachmentSerializer(instance=attachment, many=True).data Error: I've tried the following ways and without success... def __str__(self): return str(self.name) def __str__(self): return self.name or '' def __str__(self): return self.get_full_name This error happens when I try to open the screen to … -
Bulk Create catch exceptions in Django
I'm trying to create 30,000 objects in Django but need the error response for each object. Bulk create with ignore conflicts as True will partially create which is not what I want and ignore conflicts as False will stop at the first error. Is there any efficient way to catch error at each row without hitting database 30,000 times? -
Jinja2 Email Template
Using Jijna2, I'm trying to make a responsive HTML email template which is almost simple <!DOCTYPE html> <html> <body> <p><strong>Hello</strong>,</p> <p>Below are the deals running on <a href="https://www.{{ url }}.com">{{ url }}</a> at <strong>{{ date }}</strong>:</p> <p>&nbsp;</p> <ul> {% for image in images %} <a href="{{ image }}"> <img src="{{ image }}" width=500" height="200"> </a> {% endfor %} </ul> <p><strong>Regards,</strong></p> <p>Team</p> </body> </html> That's what is shown currently: and during full screen: How to make it responsive in this case and keep the display of images one by one. not side by side during full screen or mobile screen! -
Static files not found when deploying Django project on Heroku
I'm writing a project with a TypeScript/React frontend built using Webpack and a backend run by Django. Running npm run build and then ./manage.py collectstatic works fine locally. But I'm running into problems trying to deploy my project on Heroku. Here's what I get when I run git push heroku main: Enumerating objects: 19, done. Counting objects: 100% (19/19), done. Delta compression using up to 4 threads Compressing objects: 100% (9/9), done. Writing objects: 100% (10/10), 1.26 KiB | 644.00 KiB/s, done. Total 10 (delta 7), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpacks: remote: 1. heroku/nodejs remote: 2. heroku/python remote: -----> Node.js app detected remote: remote: -----> Creating runtime environment remote: remote: NPM_CONFIG_LOGLEVEL=error remote: NODE_VERBOSE=false remote: NODE_ENV=production remote: NODE_MODULES_CACHE=true remote: remote: -----> Installing binaries remote: engines.node (package.json): unspecified remote: engines.npm (package.json): unspecified (use default) remote: remote: Resolving node version 14.x... remote: Downloading and installing node 14.17.1... remote: Using default npm version: 6.14.13 remote: remote: -----> Restoring cache remote: - node_modules remote: remote: -----> Installing dependencies remote: Installing node modules remote: added 5 packages in 0.409s remote: remote: -----> Build remote: remote: … -
Celery task remains 'pending'
I configured a Celery instance like this: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery( 'project', broker='amqp://', backend='amqp://localhost' ) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') I have a task: @shared_task(bind=True) def task(self, X): self.update_state(state='PENDING') time.sleep(2) print (X) output = sum(X) self.update_state(state='COMPLETE') return output When I call the task and check its state, it's always 'PENDING'. task = task.delay(features) task_id = task.task_id state = AsyncResult(id=task_id).state But the terminal shows: [2021-06-30 16:11:00,072: INFO/MainProcess] Task spotify.tasks.AffinityPropagation_task[09a1812b-1044-480a-a0fb-49be2e5cdc94] received [2021-06-30 16:11:02,077: INFO/ForkPoolWorker-2] Task spotify.tasks.AffinityPropagation_task[09a1812b-1044-480a-a0fb-49be2e5cdc94] succeeded in 2.002569585999993s: 4 Which is confusing to me. I read other issues, but those were mostly related to a bug on Windows. I'm running on Mac. What am I missing here? Suggestions are much appreciated. -
How to create management command to email a password reset?
Using the django-oauth-toolkit, I have to create a management command that would send a password reset email off to an email address. This email would have an html template and allow the user to change their password. I can see that the view has this logic, but instead provides a template to enter the email address. I need to mimic this view, and create a command to do it. The password_reset url returns this view and form. class PasswordResetView(PasswordContextMixin, FormView): email_template_name = "registration/password_reset_email.html" extra_email_context = None form_class = PasswordResetForm from_email = None html_email_template_name = None subject_template_name = "registration/password_reset_subject.txt" success_url = reverse_lazy("password_reset_done") template_name = "registration/password_reset_form.html" title = _("Password reset") token_generator = default_token_generator @method_decorator(csrf_protect) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def form_valid(self, form): opts = { "use_https": self.request.is_secure(), "token_generator": self.token_generator, "from_email": self.from_email, "email_template_name": self.email_template_name, "subject_template_name": self.subject_template_name, "request": self.request, "html_email_template_name": self.html_email_template_name, "extra_email_context": self.extra_email_context, } form.save(**opts) return super().form_valid(form) I do not need the form bit, I need to send the email. class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument("email", type=str) def handle(self, *args, **options): // call logic for email in here ?? but how The below method seems important as well. But the management commands are outside the context of a view, which handles the … -
Issues with Custom Error Messages on ModelForm
I am trying to override the default error messages So that I could myself define some sentences for the errors but I am unable to override and it's really killing my time. Does Someone know what am I missing? from django import forms from django.forms import ModelForm from django.utils.translation import ugettext_lazy from .models import * # Create your models here. class ProfileForm(ModelForm): error_messages = { 'required': ugettext_lazy("This field is mandatory."), 'invalid': 'Enter a valid number', 'caps': 'This field if case sensitive' } esewa_id = forms.CharField(error_messages=error_messages, label='Esewa_Id', help_text='This information will be used only for payment purpose.', widget=forms.NumberInput(attrs={'class':'NumberField', 'type':'number', 'placeholder':'Enter your Esewa_Id'}), ) class Meta: model=Customer fields = ['first_name','second_name','email','image','gender','esewa_id'] In models.py I have define a Customer model that inherits from the User model and also use validators for the image validation and did mention help_text. from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.core.validators import FileExtensionValidator,MinValueValidator,MaxValueValidator # Create your models here. class Customer(models.Model): Gender_Choices=[ ('Male','Male'), ('Female','Female'), ] user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) first_name = models.SlugField(max_length=10, null=True) second_name=models.CharField(max_length=10,null=True) email = models.EmailField(max_length=140, null=True,blank=True) image = models.ImageField(upload_to="thumbnails/profile/%y" ,help_text="This will be uploaded as your profile picture. Only .png and .jpg are accepted" ,validators=[FileExtensionValidator(['png','jpg'])] ,blank=True,null=True) gender=models.CharField(choices=Gender_Choices,null=True,max_length=50) esewa_id=models.PositiveIntegerField(null=True ,help_text='This information will be … -
instance.user.id inside user_directory_path
How to access and use the uploader's user id in a Django model? Specifically, an example hereabout on using instance.user.id in the upload path, results in an AttributeError simply because a MyModel object as the instance has no attribute user. def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.FileField(upload_to=user_directory_path) -
Django Postgresql Search Not Showing Results
I'm making a Django website that has Full Text Search with Postgres. However, when I make my search, none of the results show up. Is there anything I did wrong? Here's my code: Views.py from django.shortcuts import render from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank from django.views.generic import ListView, FormView from .models import Post from .forms import * # Create your views here. class HomepageView(FormView): template_name = 'selling/home.html' form_class = SearchForm class Search(ListView): model = Post template_name = 'selling/search.html' def get_queryset(self): query = self.request.GET.get('q') posts = Post.objects.annotate( search=SearchVector('title', 'description'), ).filter(search=SearchQuery(query)) return posts Models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title = models.CharField(max_length=100) description = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) book_author = models.CharField(max_length=30) phone_contact = models.CharField(max_length=20) price = models.DecimalField(max_digits=7,decimal_places=2) postal_code = models.CharField(max_length=20) def __str__(self): return self.title Forms.py from django import forms class SearchForm(forms.Form): q = forms.CharField(label='Search', max_length=50) Search.html {% extends "selling/base.html" %} {% load static %} {% block content %} <div class="container pt-5 pb-5"> <div class="ui divided items"> {% for item in posts %} <div class="item"> <div class="image"> <img src="{% static 'selling/images/brebeuf.png' %}"> </div> <div class="content item-container"> <a class="header item-title">{{ item.title }} </a><b class="item-price-right">${{ item.price }}</b> … -
How to solve this error AttributeError at /vendor/profile 'NoneType' object has no attribute 'created_at'. I want to create multiple vendors profile
I want create multiple vendors profile accounts. I want in my site their are two profiles one customer profile and second is vendor profile. But i cannot do that. Can anyone tell me how i will be create those two profiles. Where vendors can upload their each products. Here is my code : from django.db import models from django.contrib.auth.models import User class VendorUser(models.Model): user = models.OneToOneField(User, related_name='vendor', on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username class VendorProfile(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) email = models.CharField(max_length=50, blank=True, null=True) phone = models.CharField(max_length=50) address = models.CharField(max_length=50, blank=True, null=True) vendor = models.ForeignKey(VendorUser, on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['first_name'] def __str__(self): return self.first_name views.py def vendor_profile(request): form = VendorProfileForm() if request.method == 'POST': form = VendorProfileForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.vendor.user.username = request.user user.save() return redirect('home') context = { 'user': form } return render(request, 'vendor/profile.html', context) forms.py class VendorProfileForm(forms.ModelForm): class Meta: model = VendorProfile fields = ('first_name', 'last_name', 'email', 'phone', 'address', 'vendor') widgets = { 'first_name' : forms.TextInput(), 'last_name' : forms.TextInput(), 'email' : forms.TextInput(), 'phone' : forms.TextInput(), 'address' : forms.TextInput(), 'vendor': forms.Select(), } -
CKEditor deleting <video> tags
I've added some tags in a CKEditor instance using the following code (loading from a Django-AJAX request). let newEl = CKEDITOR.dom.element.createFromHtml( `<video height='320' width='500' controls autoplay playsinline src='${url}'></video>` ); CKEDITOR.instances.q_body.insertElement(newEl); It loads correctly in the browser, but on hitting save, and after going to the same page, every video tag has been stripped out and no longer renders. I've tried numerous attempts and plugins, but nothing is working. I'll appreciate any help with this. -
wfastcgi-enable failed to create process
When I install python first time, wfastcgi-enable didn't have any problem. But when I uninstall and reinstall it happened like above! My python install place. C:\Users\Civil\Python38 Command Prompt C:\Windows\system32>pip install wfastcgi Collecting wfastcgi Using cached wfastcgi-3.0.0.tar.gz (14 kB) Using legacy 'setup.py install' for wfastcgi, since package 'wheel' is not installed. Installing collected packages: wfastcgi Running setup.py install for wfastcgi ... done Successfully installed wfastcgi-3.0.0 C:\Windows\system32>wfastcgi-enable failed to create process. -
Django IntegrityError NOT NULL constraint failed not use null and blank
IntegrityError at /blablabla NOT NULL constraint failed: modal_modal.examples Null=True, blank=True is suggested as a solution to this error. But I don't want it to be null and blank. How do I solve it without adding blank and null? -
How to add buttons in datatable server-side in Django?
i may need some help with datatable server-side based in Django. In the beginner i was using datatable without server processing and it became very slow with more than 15 000 rows This was my interface before i moved to django-datatable-view : before server side So i'm trying to add server-side datatables and i succeed to show the data with this : models.py class SysModel(models.Model): tag = models.CharField(max_length=200, primary_key=True, unique=True) description = models.CharField(max_length=200) explanation = models.TextField(blank = True) recommandations =models.TextField(blank = True) component = models.CharField(max_length=50, blank = True) severity = models.CharField(max_length=50, blank = True) views.py from django_datatables_view.base_datatable_view import BaseDatatableView from django.views.generic import TemplateView class XEList(TemplateView): template_name = 'table/sys/index.html' class XEJson(BaseDatatableView): model = SysModel columns = ['tag','description','explanation','recommandations','component','severity'] order_columns = ['tag','description','explanation','recommandations','component','severity'] max_display_length = 500 template html + JS <table class="datatable"> <thead> <th>Tag</th> <th>Description</th> <th>Explanation</th> <th>Recommended Action</th> <th>Component</th> <th>Severity</th> </thead> </table> <script> $(document).ready(function() { var dt_table = $('.datatable').dataTable({ order: [[ 0, "desc" ]], lengthMenu: [[25, 50, 100, 200], [25, 50, 100, 200]], searching: true, processing: true, serverSide: true, stateSave: true, ajax: TESTMODEL_LIST_JSON_URL }); }); </script> I get this interface now : enter image description here and i want to add my old edit and delete buttons But when i try to add a …