Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass multiple key-value pairs as query parameter in Python Django?
I am building a key-value store REST API that will store data in a key value pair. Suppose I want to create an endpoint where I can make a GET request to values/ to get one or more values by passing one or more keys just like this: /values?keys=key1,key2,key3 I want to know what should I do in urls.py if I want to do this variable length query. This is my model: class Data(models.Model): key = models.CharField(max_length = 100) value = models.CharField(max_length = 1000) def __str__(self): return '{}:{}'.format(self.key, self.value) -
Can I receive notifications about new IP addresses connected to my server?
I have a django website deployed on AWS EC2 behind Nginx, without wsgi right now (I'm still in the early stage of development and checking my options). I've noticed in my nginx access log a few new IP addresses, that are not mine. Is there any tool available to send notifications about new connections? I can develop a script for that, but maybe there is a tool already within some wsgi or Nginx. p.s. I've tried https://softwarerecs.stackexchange.com/ with no luck. -
Django Rest Framework nested serializer validate data
i'm begginer in DRF and i'mtrying to create 2 signup forms with a profile (Buyer and Seller) using a Custom User model common to both, through a nested serializer, but when i create a new user with those serializer my password is not being hashed,generating some problems with rest_auth login. How can i validate my password in a nested serializer? This is a good approach to create a 2 types custom signup form? Here is my code Models. Py class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class BuyerProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) first_name = models.CharField(max_length = 100,blank = False) last_name = models.CharField(max_length = 100,blank = False) password = models.CharField(max_length = 10, default = False) def __str__(self): return self.email SELLER_CHOICES = (('1',"Company"),('2','Person')) SELLERPRODUCT_CHOICES = (('1','Food'),('2','Drinks')) class SellerProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) company_name = models.CharField(max_length= 100,unique=True) company_phone = models.CharField(max_length= 100) company_zip = models.CharField(max_length= 50) company_phone = models.CharField(max_length= 50) seller_type = models.CharField(max_length = 50 ,choices =SELLER_CHOICES,default ='1') seller_product = models.CharField(max_length = 50 ,choices =SELLERPRODUCT_CHOICES,default ='1') def __str__(self): return self.company_name Serializers.Py class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'password') def create(self, … -
Deploying Django to Heroku - psycopg2.errors.UndefinedColumn: column "text" does not exist
I am trying to deploy Django to Heroku for the first time, using the command. heroku run python manage.py migrate I receive the following error however that the column "text" does not exist, any advice on how to resolve this? There should not be any models named 'text' in the database. Applying charity_app.0002_auto_20191222_1634...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column "text" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column "text" does not exist Many thanks in advance. -
Django is not re-rendering css & JS via DetailView
I used inline formsets in the DetailView class. class DetailView(DetailView) In order to display the page correctly, I used the get_context_data function: def get_context_data(self, *args, **kwargs): context = super(QuestionDetailView, self).get_context_data(**kwargs) context['formset'] = self.get_formset() context['question'] = self.get_object() return context css and JS worked well on this page. However, I don’t know how to make the page also render well if the formset is invalid def post(self, request, slug): [...] formset = self.AnswerFormset(request.POST, instance=self.get_object()) # create/edit an answer if formset.is_valid(): return self.form_valid(formset, slug) else: return render(request, 'questions/detail.html', {'slug': slug, 'formset': formset,'question':self.get_object()}) def form_valid(self, formset, slug): formset.save() return redirect('questions:question_detail', slug=slug) If the formset is valid, then all styles and Java script work well. If the form is invalid, then the styles and script located on the questions/detail.html do not work. I spent a lot of time trying to convey errors in some way to get_context_data, but I failed and rendered the page separately (return render(request, 'questions/detail.html', {'slug': slug, 'formset': formset,'question':self.get_object()}) Do you have any idea on how to render the page with form errors correctly? Cheers -
Error when overriding views auth page in django
In my project, I have an app namely account, I put my login.html and logged_out.html files in templates/registration directory. In urls, I use django.contrib.auth.views to call the ones, as below from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('logout/', auth_views.LogoutView.as_view( template_name="logged_out.html"), name='logout'), path('login/', auth_views.LoginView.as_view( template_name="registration/login.html"), name='login'), ] The problem is my login page is my login page loaded successful, but the logged_out page is not, it just the default logged_out page. I tried to move the logged_out.html file to other directory and it was loaded. So my question is why I cannot override the logged_out page while I can do it with login page. Note: I try with other page like change passwords and still got the same errors. -
Parent Model of Django Formset Saves Twice
I have two models, a basic parent and a child. The child model is an inline formset. When I create the parent and the child objects together in a template, the parent model is saved twice. As I understand it, the parent must be created to get the parent_id to be used as the FK for the child object. Once the child object is saved, the parent also seems to be saved a second time when the form is validated. Because I am using signals, it is very inconvenient to have the parent model saved twice when a new parent object is created as it triggers my signals twice. As a work-around, I have added a save_count field so I can use conditional statements that avoid certain actions on the first save. Is there a way in Django to have the parent object only save once with inline formsets? #views.py class ParentCreateView(LoginRequiredMixin, CreateView): model = Parent template_name = "parent/parent_new.html" form_class = NewParentForm def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data["child"] = ChildInlineFormSet( self.request.POST, instance=self.object, prefix="child" ) else: data["child"] = ChildInlineFormSet( instance=self.object, prefix="child" ) return data def form_valid(self, form): context = self.get_context_data() child = context["child"] form.instance.save_count += 1 with transaction.atomic(): … -
Make migrations error in django: "no such table"
when i was trying to make magirations: python manage.py makemigrations The following error occurred: django.db.utils.OperationalError: no such table: blog_category Traceback (most recent call last): File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django \db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: blog_category The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django \core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 361, in execute self.check() File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 571, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 564, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\injemam\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", … -
In server it showes an error like [Errno 5] Input/output error
When run in server it shows an error like [Errno 5] Input/output error,but it is work on localhost,can you solve this issue urls.py url(r'followpopularnewsprovider/(?P<user_id>\d+)/$', csrf_exempt(views.GetMobilefollowpopularnewsproviderTest), name='popularprovider'), views.py def dictfetchall(cursor): """Return all rows from a cursor as a dict""" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] def GetMobilefollowpopularnewsproviderTest(request,user_id): if request.method == 'GET': cursor = connection.cursor() queryset = cursor.execute("select crawl_newsproviders.id,crawl_newsproviders.provider,crawl_providers.url,crawl_providers.region, crawl_providers.image,crawl_providers.description,crawl_providers.followers,crawl_providers.slug,crawl_providers.created_time,crawl_providers.publish,1 as status from crawl_providers join accounts_followprovider on crawl_providers.id=accounts_followprovider.provider_id where accounts_followprovider.user_id='%s' union select crawl_providers.id,crawl_providers.provider,crawl_providers.url,crawl_providers.region, crawl_providers.image,crawl_providers.description,crawl_providers.followers,crawl_providers.slug,crawl_providers.created_time,crawl_providers.publish,0 from crawl_providers where crawl_providers.provider not in(select crawl_providers.provider as id from crawl_providers join accounts_followprovider on crawl_providers.id=accounts_followprovider.provider_id where accounts_followprovider.user_id='%s');"%(user_id,user_id)) dict = {} dict = dictfetchall(cursor) print(dict) context = { 'posts': dict } cursor.close() return JsonResponse(context) return HttpResponse(status=201) -
Django You should not have DEBUG set to True in deployment. (security.W018)
When I do the deployment checklist, I get many errors: one of them is this one: ?: (security.W018) You should not have DEBUG set to True in deployment. which I don't understand and I don't find anything anywhere telling me how to fix it. -
Getting error : AttributeError: 'QuerySet' object has no attribute 'usertype' in django
I am working on login api, when i tried to run this command user_profile = UserProfile.objects.filter(user_id=user.id).values('usertype') It gives me this error : AttributeError: 'QuerySet' object has no attribute 'usertype' but in console i checked i am getting its queryset <QuerySet [{'usertype': 2}]> but not able to fetch the value from it, can anyone please help me how to resolve this issue ? here is my signin function of it class Login(APIView): permission_classes = (AllowAny,) def post(self, request): username = request.data.get("username") password = request.data.get("password") if username is None or password is None: return Response({'success': False, 'error': 'Please provide both username and password'}, status=HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) # return Response({'success': True, 'user': user},status=HTTP_200_OK) if not user: return Response({'success': False, 'error': 'Invalid Credentials'}, status=HTTP_400_BAD_REQUEST) access_token, refresh_token = utils.generate_tokens(user) user_profile = UserProfile.objects.filter(user_id=user.id).values('usertype') print(user_profile.usertype) -
show one page for all error response in django
I want to show one special page for all error responses in Django. as following this issue Django, creating a custom 500/404 error page I add these items to my project files. but nothing changed! setting.py DEBUG = False ALLOWED_HOSTS = ['localhost'] urls.py handler500 = 'app.views.handler500' views.py from django.shortcuts import render_to_response from django.template import RequestContext def handler500(request, *args, **argv): response = render_to_response('app/500.html', {}, context_instance=RequestContext(request)) response.status_code = 500 return response -
How to open modal in django after ajax query
I have a update form in my project which return JsonResponse(data). The main issue is I don't know how to correctly define url in ajax function to open a bootstrap modal after ajax success. My code: $.ajax({ url: , type: 'get', success: function(data) { console.log(data); }, }); -
Django: Custom permission has no effect and check within view returns error
I have a generic view (CreateAPIView) with a custom permission class TransactionCreatorIsSenderOrAdmin but it has no effect on the view at all, even if the permission class contains nothing but return False. I think the reason for this is stated in the documentation: Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the filtering documentation for more details. Since I am retrieving more than one model instance, my approach was to do the check within the view itself, inside perform_create, but I get an error and I am not sure why, cause it works without the permission check. Here is the error: Exception Type: AttributeError Exception Value: 'collections.OrderedDict' object has no attribute 'date' Exception Location: .../transactions/api/serializers.py in get_date, line 17 Here is my view: class TransactionCreateAPIView(generics.CreateAPIView): queryset = Transaction.objects.all() serializer_class = TransactionSerializer permission_classes = [IsAuthenticated, TransactionCreatorIsSenderOrAdmin] def perform_create(self, serializer): amount = self.request.data['amount'] message = self.request.data['message'] from_account_iban = self.request.data['from_account'] from_account_obj = BankAccount.objects.get(iban=from_account_iban) to_account_iban = self.request.data['to_account'] to_account_obj = BankAccount.objects.get(iban=to_account_iban) if from_account_obj.user == self.request.user or self.request.user.is_staff == True: serializer.save(amount=Decimal(amount), from_account=from_account_obj, to_account=to_account_obj, message=message) else: return Response(serializer.errors, status=403) … -
__init__() got an unexpected keyword argument 'region'
I'm developing a user registration app, I'm following a series of videos (https://codingwithmitch.com/courses/building-a-website-django-python/) but customize it the way I need it. Here's my models.py in my account app: from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, username, email, first_name, last_name, password=None): if not username: return ValueError("وارد نمودن شماره تلفن همراه الزامیست") if not email: return ValueError("وارد نمودن ایمیل الزامیست") if not first_name: return ValueError("وارد نمودن نام الزامیست") if not last_name: return ValueError("وارد نمودن نام خانوادگی الزامیست") user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, first_name, last_name, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, first_name=first_name, last_name=last_name, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): username = PhoneNumberField(verbose_name='شماره تلفن همراه', max_length=15, unique=True) first_name = models.CharField(verbose_name='نام', max_length=15) last_name = models.CharField(verbose_name='نام خانوادگی', max_length=40) email = models.EmailField(verbose_name='ایمیل', max_length=60, unique=True) date_joined = models.DateTimeField(verbose_name='تاریخ ملحق شدن', auto_now_add=True) last_login = models.DateTimeField(verbose_name='آخرین بازدید', auto_now=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) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'first_name', 'last_name', ] objects = MyAccountManager() def __str__(self): return str(self.username) + ', ' + self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, … -
Django outputting errorlist as string instead of html
I'm trying to customize the default error list in django. I've tried following the docs, but the problem is that the supposed html gets outputted as text istead of html: I'm not quite sure why this is happening, as the code is pretty much copy-paste from the docs. Code: forms.py class DivErrorList(ErrorList): def __str__(self): return self.as_divs() def as_divs(self): if not self: return '' return '<div class="test">%s</div>' % ''.join(['<div class="error">%s</div>' % e for e in self]) views.py def addUser(request): add_user_form = AddUserForm() messages.warning(request, 'message') if request.method == 'POST': add_user_form = AddUserForm(request.POST, error_class=DivErrorList) if add_user_form.is_valid(): user = add_user_form.save() customer_group = Group.objects.get(name = 'group_name') user.roles.add(customer_group) messages.success(request, 'message') return redirect('users') else: messages.error(request, 'message') context = { 'add_user_form': add_user_form, } return render(request, 'users/backend/user/user_add.html', context) html <div class="w-full mt-6"> {% include 'components/typography/form_label.html' with label='Gjenta passord' %} {{ add_user_form.password2 }} {{ add_user_form.password2.errors }} </div> -
Django Uplaod and show multiple images
This is my Model Post where i want to uplaod multiple pictures for a specific post,so i have created foreign key from PostPicture to Post . ''' class Post(models.Model): title = models.CharField(max_length=200, unique=True) # image = models.FileField(null = True, blank=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) #code for Thumbnail # image = models.ImageField(upload_to = "media", default='DEFAULT VALUE') image_thumbnail = ProcessedImageField(upload_to = "thumbnail", processors = [ResizeToFill(100,50)],format = 'JPEG',options = {'quality':60},default='DEFAULT VALUE') class Meta: ordering = ['-created_on'] def __str__(self): return self.title #code for uploading multiple images class PostPicture(models.Model): picture =models.ImageField(upload_to="blog_images", blank=True) postid =models.ForeignKey(Post,on_delete=models.CASCADE,related_name='pictures') ''' This is my template code where i am iterating through the pictures and trying to show them. {% for i in post.pictures.all %} <img src = "{{ post.pictures.url }}" height = "200", width="200"/> {% endfor %} I am using admin to add the blog post , attaching ss to have a look at the admin. enter image description here This is the output on the UI, i am not getting the images to show up here. enter image description here Can anyone help me ,where i am going wrong -
Django refuses request from Python requests
I have a Django view where when a user performs a certain task, an external Python microservice retrieves and then sends some data to the Django view, which is supposed to show it to the user on the template. To send the data i'm using Python requests, the problem is that the Json response is being refused by Django for two reasons: 1) The CSRF Token is not set 2) The view is @login_required Here is my view: @login_required def myTestView(request): if request.method == 'POST': received_json_data=json.loads(request.body) print(received_json_data) print('received.') And here is how i send the response: import requests req = requests.post('http://127.0.0.1:8000/myTestView/', json={"test": "json-test"}) print('SENT') With the actual code, i get this error from Django: Forbidden (CSRF cookie not set.): /myTestView/ [2019-12-24 15:36:08,574] log: WARNING - Forbidden (CSRF cookie not set.): /myTestView/ I know i can use @csrf_exempt, but since the data that i'm sending is personal, i would like it to be as safe as possible, so i need to find a way to send the CSRF Token. The second thing i need to do, is how do i "login" using the request? -
Django reset password fail
I'm currently adding a way of reseting a user password for the website I develop. For that purpose, I used the built-in view of Django. You can find the relevant part of all the files below : urls.py urlpatterns = [ path('recuperation-mot-de-passe', auth_views.PasswordResetView.as_view(email_template_name='inscription/reset_mail.html', subject_template_name='inscription/subject_mail.txt', success_url='recuperation-envoyee'), name = 'password-reset'), path('recuperation-envoyee', auth_views.PasswordResetDoneView.as_view(), name = 'password-reset-done'), path('recuperation-confirmee/<uidb64><token>', auth_views.PasswordResetConfirmView.as_view(success_url='recuperation-complete'), name = 'recuperation-confirmee'), path('recuperation-complete', auth_views.PasswordResetCompleteView.as_view(), name = 'password-reset-complete'), ] reset_mail.html {% load i18n %}{% autoescape off %} {% blocktrans %}Vous recevez cet email car vous avez demandé à réinitialiser le mot de passe associé à votre compte Cook4Me.{% endblocktrans %} {% trans "Cliquer sur ce lien pour choisir un nouveau mot de passe :" %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'recuperation-confirmee' uidb64=uid token=token %} {% endblock %} {% trans "Votre identifiant, au cas où vous l'auriez oublié :" %} {{ user.get_username }} {% trans "Merci d'utiliser Cook4Me !" %} {% blocktrans %}L'équipe Cook4Me{% endblocktrans %} {% endautoescape %} When I test all of this, the following problem happens : First, I enter my email address. The mail is correctly sent but I receive twice the same mail which I think is a first problem. The big problem is when I … -
Django : Using selected radio button's value in views to update value in database
I am trying to write a view where the selected radio button's value/id ( not sure ) will be passed to django view after clicking submit and then that value should be stored in a column for a particular user and the question to which the radio button held an answer. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) labels=[] for i in range(1,16): labels.append('a'+str(i)) for label in labels: Profile.add_to_class(label, models.CharField(max_length=255, default='NULL', blank='NULL')) class Image(models.Model): p_img = models.ImageField(max_length=255,upload_to='p_image',default='NULL', blank='NULL') p_img_count = models.IntegerField(default=0) s_image1 = models.ImageField(max_length=255,upload_to='s_image') s_image2 = models.ImageField(max_length=255,upload_to='s_image',default='NULL', blank='NULL') s_image3 = models.ImageField(max_length=255,upload_to='s_image',default='NULL', blank='NULL') s_image4 = models.ImageField(max_length=255,upload_to='s_image',default='NULL', blank='NULL') s_image5 = models.ImageField(max_length=255,upload_to='s_image',default='NULL', blank='NULL') def __str__(self): return(str(self.p_image)) class Score(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) points = models.IntegerField() def __str__(self): return(self.username) views.py def update_db(request): # getting selected radio button value and use to it update that particular user's answer in Profile model. return render(request, index.html, {}) index.html <form action='/update' > <p style="background-color: #ddd674">Primary image :<img src="{{media_url}}{{ p_img.p_img }}" height=300px > <br> </p> <hr height=2px > <p style="background-color: #a7e0d9">Secondary image : {% for img in s_img %} {% if img %} <input type="radio" id="{{ img }}" name="ans" > <img src="{{media_url}}{{ img }}" height=250px > </input> {% endif %} {% endfor %} <br> </p> <button type="submit" name="next" class="btn … -
runserver can't serve media if MEDIA_URL is within STATIC_URL
My config is as follows: STATIC_URL = '/static/' MEDIA_URL = '/static/media/' And since I upgraded django 2.0 to 2.2.9 I get: "runserver can't serve media if MEDIA_URL is within STATIC_URL." django.core.exceptions.ImproperlyConfigured: runserver can't serve media if MEDIA_URL is within STATIC_URL. I understand the error. My question is "why not"? There are very valid reasons you'd want media as a subdirectory to static. -
Testing django view with form that contains ModelChoiceField
Here is the form that am using to send data to the view : class RegisterForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': _('User Name') })) password = forms.CharField(widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': _('Password') })) roles = forms.ModelChoiceField(queryset=Role.objects.exclude(role_name="Admin"), widget=forms.Select(attrs={ 'class': 'form-control', })) And Here is the view am testing with the form in it : def register(request): user = request.user current_user = CustomUser.objects.get(username=user.username) if current_user.role.role_name == "Admin": register_form = RegisterForm(request.POST) if request.method == "POST": if register_form.is_valid(): username = register_form.cleaned_data['username'] password = register_form.cleaned_data['password'] role = register_form.cleaned_data['roles'] if CustomUser.objects.filter(username=username).exists(): messages.error(request, _('Username already exists.')) else: new_user = CustomUser.objects.create_user(username=username, password=password, role=role) messages.success(request, _('User created Successfully')) return redirect("user_details", pk=new_user.pk) else: register_form = RegisterForm(request.POST) context = { 'register_form': register_form, } return render(request, 'register.html', context) else: messages.error(request, _('You are not allowed to view this page.')) return redirect('index') Here is how I try to test it by sending post request (reverse) with data: def test_post_request_correct_date(self): call_command("start_app") self.client.login(username='user', password='pass') waiter_role = Role.objects.get(role_name="Waiter") url = reverse('register') data = { 'username': 'new_user', 'password': 'just good password', 'roles': waiter_role.pk } response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 302) new_user = CustomUser.objects.get(username="new_user") self.assertRedirects(response, reverse('user_details', args={"pk": new_user.pk})) self.assertTemplateUsed(response, 'user_profile.html') please note that call_command("start_app") is custom command that creates the roles i choose from it. I get this … -
How to implement push notifications in Django?
I'm in a region blocked by Google and other big techs push notification services and have to implement it myself; So I want to know the best practices and ideas of how I can do it, cause almost every tutorial assumes I'm using one of the aforementioned services which is not applicable. Requirements: There are some providers and some customers in my service; A specific provider should want to alert a specific customer and I want it to happen in near real-time (will happen very frequently with so many providers and many customers). Should I consider implementing it via WebSocket? If so I'll appreciate introducing some resources as well. -
Defining different schema for both get and post request - AutoSchema Django Rest Framework
I am trying to define AutoSchema(to be shown in django rest framework swagger) for my rest api in django rest framework. There's this class that extends APIView. The class has both 'get' and 'post' methods. Like: class Profile(APIView): permission_classes = (permissions.AllowAny,) schema = AutoSchema( manual_fields=[ coreapi.Field("username", required=True, location='query', description='Username of the user'), ] ) def get(self, request): return schema = AutoSchema( manual_fields=[ coreapi.Field("username", required=True, location='form', description='Username of the user '), coreapi.Field("bio", required=True, location='form', description='Bio of the user'), ] ) def post(self, request): return The problem is I want different schema for both get and post request. How can i achieve this using AutoSchema. Please help. I've been stuck here for a day. -
Filtering displayed objects in django view
I am learning Django. Currently I build my blog project. I want to add function to filter posts by date (you can choose specific date from combo box and click "filter" button and then on the main page will display only this posts which were created in this date). Since I'm still new to django, I'm struggle how to handle it. My question is how to build a functionality that will extract the sent date from the combo box and pass it to the view where I will do the appropriate filtering in the get_queryset method. Below I publish my code: Part of my .html file where I build combo box: <p class='text-muted'>Choose date from the list below.</p> <form method="GET"> <select name="date_filter"> <option>-----------------</option> {% for post in posts %} <option>{{ post.date_posted }}</option> {% endfor %} </select> <button type="submit" class="btn btn-info btn-sm mt-1 mb-1">Filter</button> </form> I would also like each date to be unique and displayed only once. Currently, each date is displayed as many times as many posts were created that day because DateTimeField in my model also stores the post creation hour. Main page view where post are displayed - in my views.py file: class PostListView(ListView): model = Post …