Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError at / 'NoneType' object is not callable
this is the code. kindly tell me what i'm doing wrong ... def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this page') return wrapper_func return decorator def admin_only(view_func): def wrapper_function(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == 'customer': return redirect('user-page') if group == 'admin': return view_func(request, *args, **kwargs) return wrapper_function -
static file loading problems on pythonanywhere
i'am trying to deploy restframework on pythonanywhere so i can use it in for my android project but the issues here that the restframework page is shown whitout a css or js files [enter image description here][1] [1]: https://i.stack.imgur.com/ImW94.png i tried evrey solution on stackoverflow but nothing work ! i collectstatic file using python manage.py collectstaticfile i set up `STATIC_ROOT='/home/ssmedicament/api/static/'` `STATIC_URL = '/static/'` -
How do I get FormSet to validate in my view?
I am doing something a bit unusual with FormSets. I am attempting to use a queryset as the input to my formset. This seems to be working at this point just fine. What isn't working is the form validation. Thanks in advance for any thoughts. I can't create this relationship via a traditional foreign key for reasons I won't bother people with. My Models.py class Team(models.Model): team_name = models.CharField(max_length=264,null=False,blank=False) class Player(models.Model): player_name = models.CharField(max_length=264,null=False,blank=False) team_pk = models.integerfield(Team,null=True,on_delete=models.CASCADE) My views.py class CreateTeamView(LoginRequiredMixin,UpdateView): model = Team form_class = CreateTeamForm template_name = 'create_team.html' def get_context_data(self, **kwargs): context = super(CreateTeamView, self).get_context_data(**kwargs) dropdown = self.request.GET.get("dropdown", None) queryset = Player.objects.filter(company_pk=dropdown) player_form = PlayerFormSet(queryset=queryset,dropdown=dropdown) context['player_form'] = player_form context['dropdown'] = dropdown return context def get_form_kwargs(self): kwargs = super(CreateTeamView,self).get_form_kwargs() kwargs['user'] = self.request.user kwargs['dropdown'] = self.request.GET.get("dropdown") return kwargs def get(self, request, *args, **kwargs): dropdown=self.request.GET.get("dropdown") self.object = self.get_object() context = self.get_context_data(object=self.object) self.object = None context = self.get_context_data(object=self.object) form_class = self.get_form_class() form = self.get_form(form_class) form_kwargs = self.get_form_kwargs() player_form = PlayerFormSet(dropdown=dropdown) return self.render_to_response( self.get_context_data(form=form, player_form=player_form, context=context, )) def form_valid(self, form, player_form): self.object = form.save() player_form.instance = self.object player_form.save() def form_invalid(self, form, player_form): return self.render_to_response( self.get_context_data(form=form, player_form=player_form, )) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) dropdown=self.request.GET.get("dropdown") player_form … -
Can I use a 6-digit pin code instead of password in logging in my users in django authentication?
Is there a way where the users can login to my webapp using their username and a 6-digit pin (like the ones we use in our atms) instead of using the password? I am new to django and don't know how or where to look in this. Thank you! -
Django URL path not matching
I am currently having a non-matching URL error for the following URL http://127.0.0.1:8000/report/?report=Report. The questions/answers found here and elsewhere have been of no use. I have a button that I am trying to redirect with. report/ ?report=Report [name='candidate-report'] The current path, report/, didn't match any of these. project.urls: from django.urls import include, path from . import views urlpatterns = [ path('', views.home_view, name='home'), path('report/', include('Reports.urls')) ] Reports.urls: from django.urls import path from . import views urlpatterns = [ path('?report=Report', views.candidate_report_view, name='candidate-report'), ] Reports.views: from django.shortcuts import render from .forms import CandidateReportForm def candidate_report_view(request): category_form = CandidateReportForm.category() comment_form = CandidateReportForm.comment() return render(request, 'candidate_report.html', {'category_form': category_form, 'comment_form': comment_form}) base.html: <form class="d-inline-block float-right" action="report/" method="get"> <input class="btn btn-primary" id="report_button" name="report" type="submit" value="Report"> -
Django channels error when attempting to serve static files with devserver
I moved my project into another environment and after installing the dependencies and attempting to run the manage.py runserver - devserver I get the following error when static files are requested. Quite frankly i'm completely lost with this error, has anyone an idea what this is about? HTTP GET /static/admin/css/responsive.css 500 [0.21, 127.0.0.1:59982] Exception inside application: async_to_sync can only be applied to async functions. Traceback (most recent call last): File "/home/maxehleny/.local/share/virtualenvs/mysite-EdbyOLs2/lib/python3.6/site-packages/channels/staticfiles.py", line 41, in __call__ dict(scope, static_base_url=self.base_url), receive, send File "/home/maxehleny/.local/share/virtualenvs/mysite-EdbyOLs2/lib/python3.6/site-packages/channels/staticfiles.py", line 56, in __call__ return await super().__call__(scope, receive, send) File "/home/maxehleny/.local/share/virtualenvs/mysite-EdbyOLs2/lib/python3.6/site-packages/channels/http.py", line 198, in __call__ await self.handle(scope, async_to_sync(send), body_stream) File "/home/maxehleny/.local/share/virtualenvs/mysite-EdbyOLs2/lib/python3.6/site-packages/asgiref/sync.py", line 105, in __init__ raise TypeError("async_to_sync can only be applied to async functions.") TypeError: async_to_sync can only be applied to async functions. I quite frankly have got little to no idea where the issue could lie since I don't see how this issue coming up relates to my own code. mhh -
Sum annotated field with different cases that returns multiple rows of same objects
I have referral program in my project, and I want to calculate commission that should be paid to customers. Each order can have both referral attached and/or promocode attached. Only bigger discount applies to final price. Comission is also should be calculated according to bigger discount. On my Referral queryset I calculate it like so: if referral discount >= promocode discount: ((max discount - referral discount) * orders total price) / 100 else if referral discount < promocode discount ((max discount - promocode discount) * orders total price) / 100 With real field names is what I have now: qs = self.annotate( orders_total_old_price=Sum( 'orders__bookings__old_price', filter=orders_query, output_field=models.FloatField() ), # BEFORE DISCOUNT (used for commission calculation) commission_real=Case( When( # subtract bigger discount (promocode or referral) Q(orders__promocode__isnull=False) | Q(orders__promocode__sale__lt=F('discount') / 100), then=((F('user__broker_discount__value') - F('discount')) * F('orders_total_old_price')) / 100 ), default=( Cast( F('user__broker_discount__value') - (F('orders__promocode__sale') * 100), output_field=models.IntegerField() ) * F('orders_total_old_price')) / 100, output_field=models.FloatField(), filter=orders_query ), # <------ This annotation works fine, but in returned queryset I have multiple same objects commission=Case( When(commission_real__lt=0.0, then=0.0), default=F('commission_real'), output_field=models.FloatField(), filter=orders_query ), # only positive value or 0, shown in statistic registrations=Subquery( registrations.values('registrations'), output_field=models.IntegerField(), filter=orders_query ) ) It returns correct results, but I have multiple rows for same … -
django.core.exceptions.ImproperlyConfigured: Set the REDIS_URL environment variable
I used Django-Cookiecutter to boost start my Django development. Now after building the website and wanting to host it, my choice was python anywhere and that's because I have already hosted a website there but that website wasn't built using Django-Cookiecutter. To host It on python anywhere am currently following the Django-Cookiecutter Official docs to host on pythonanywhere I have completed the first steps till it's time to run python manage.py migrate which results in the following error: django.core.exceptions.ImproperlyConfigured: Set the REDIS_URL environment variable In Full The Error Msg is : Traceback (most recent call last): File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/environ/environ.py", line 273, in get_value value = self.ENVIRON[var] File "/home/someone/.virtualenvs/smt/lib/python3.8/os.py", line 673, in __getitem__ raise KeyError(key) from None KeyError: 'REDIS_URL' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 35, in <module> execute_from_command_line(sys.argv) File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/core/management/base.py", line 82, in wrapped saved_locale = translation.get_language() File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 252, in get_language return _trans.get_language() File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 57, in __getattr__ if settings.USE_I18N: File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in … -
How to properly work with URL mapping in Django and what a beginner needs to know
path('book/int:pk', views.BookDetailView.as_view(), name='book-detail') should we use ^ $ \d and in which situations re_path(r'^book/(?P\d+)$', views.BookDetailView.as_view(), name='book-detail') -
Tell me, is it possible that there is an error in the url?
Someone tell me, set up categories for the blog according to one old documentation, added 3 categories, all with posts, but they are not displayed, what is the problem? models.py f rom django.db import models from django.contrib.auth.models import User STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=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) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE,) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_cat_list(self): k = self.category # for now ignore this instance method breadcrumb = ["dummy"] while k is not None: breadcrumb.append(k.slug) k = k.parent for i in range(len(breadcrumb)-1): breadcrumb[i] = '/'.join(breadcrumb[-1:i-1:-1]) return breadcrumb[-1:0:-1] # Create your models here. class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.CASCADE,) class Meta: #enforcing that there can not be two categories under a parent with same slug # __str__ method elaborated later in post. use __unicode__ in place of # __str__ if you are using python 2 unique_together = ('slug', 'parent',) verbose_name_plural = "categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = … -
How to upload all rows in an excel file into django model with xlrd
How can I modify this code to accept to upload all lines of data in the excel sheet provided? Curerently it only picks the values in row 2, i.e after the headers. def UploadTeacherView(request): if request.method == 'POST': form = NewTeachersForm(request.POST, request.FILES) if form.is_valid(): excel_file = request.FILES['file'] fd, path = tempfile.mkstemp() try: with os.fdopen(fd, 'wb') as tmp: tmp.write(excel_file.read()) book = xlrd.open_workbook(path) sheet = book.sheet_by_index(0) obj=TeacherData( school_id = sheet.cell_value(rowx=1, colx=1), code = sheet.cell_value(rowx=1, colx=2), first_name = sheet.cell_value(rowx=1, colx=3), last_name = sheet.cell_value(rowx=1, colx=4), email = sheet.cell_value(rowx=1, colx=5), phone = sheet.cell_value(rowx=1, colx=6), ) obj.save() finally: os.remove(path) else: message='Invalid Entries' else: form = NewTeachersForm() return render(request,'new_teacher.html', {'form':form,'message':message}) -
Optimizing # of SQL queries for Django using "Prefetch_related" for nested children with variable level depth
I have a Child MPTT model that has a ForeignKey to itself: class Child(MPTTModel): title = models.CharField(max_length=255) parent = TreeForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="children" ) I have a recursive Serializer as I want to show all levels of children for any given Child: class ChildrenSerializer(serializers.HyperlinkedModelSerializer): url = HyperlinkedIdentityField( view_name="app:children-detail", lookup_field="pk" ) class Meta: model = Child fields = ("url", "title", "children") def get_fields(self): fields = super(ChildrenSerializer, self).get_fields() fields["children"] = ChildrenSerializer(many=True) return fields I am trying to reduce the number of duplicate/similar queries made when accessing a Child's DetailView. The view below works for a depth of 2 - however, the "depth" is not always known or static. class ChildrenDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Child.objects.prefetch_related( "children", "children__children", # A depth of 3 will additionally require "children__children__children", # A depth of 4 will additionally require "children__children__children__children", # etc. ) serializer_class = ChildrenSerializer lookup_field = "pk" Should I be overwriting get_object and/or retrieve? How do I leverage a Child's depth (i.e. the Child's MPTT "level" field) to optimize prefetching? -
AttributeError: 'method' object has no attribute 'backend'
Traceback (most recent call last): File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Internet\Desktop\Programming\Discord\Ξ X 0 Website\Ξ X 0 Dashboard\dashboard\home\views.py", line 12, in home_view authenticate(request, user=user) File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 80, in authenticate user.backend = backend_path AttributeError: 'method' object has no attribute 'backend' I'm getting this error from Django when I tried creating a custom authentication system. I'm pretty sure this is coming from my views.py but I have no idea how to fix it. All the code I worked on is down below. I did some print statements to see if the code breaks somewhere and I found that authenticate(request, user=user) in views.py stops the code which causes auth.py and managers.py to not trigger. managers.py from django.contrib.auth import models class DiscordUserOAuth2Manager(models.UserManager): def create_new_discord_user(self, user): print('Inside Discord User Manager') discord_tag = '%s#%s' % (user['username'], user['discriminator']) new_user = self.create( id=user['id'], avatar=user['avatar'], public_flags=user['public_flags'], flags=user['flags'], locale=user['locale'], mfa_enabled=user['mfa_enabled'], discord_tag=discord_tag ) return new_user auth.py from django.contrib.auth.backends import BaseBackend from .models import DiscordUser from django.contrib.auth.models import User class DiscordAuthenticationBackend(BaseBackend): def authenticate(self, request, user): find_user = DiscordUser.objects.filter(id=user['id']) if len(find_user) == 0: print("User was not found. Saving...") new_user = DiscordUser.objects.create_new_discord_user (user) print(new_user) return new_user return find_user … -
How to send axios request to localhost?
I am currently trying to send an API request from a mobile app to a django server running on my computer. I am receiving a network error every time I try and send the request, regardless of the different headers I use (I am new to this so my headers could be totally wrong). Here is the request I am sending: export async function requestPrediction(img) { const url = 'http://127.0.0.1:8000/v1/predict/'; const data = new FormData(); data.append('file', { uri: img, type: 'image/jpeg', name: 'imageName' }); try { console.log(url, data); let resp = await Axios.post(url, data, { headers: { 'accept': 'application/json', 'Accept-Language': 'en-US,en;q=0.8', 'Content-Type': `multipart/form-data; boundary=${data._boundary}`, } }); console.log('######################\n','ACTION_RESULTS_SUCCESS',resp.data); } catch(error) { console.log('######################\n','ACTION_RESULTS_ERROR', error); } } I am pretty certain the URL I am sending to is the right address. When I type that URL in on my computer while the server is running I do not receive an error that the page wasn't found. Thanks for the help. I can post any server-side code that might be necessary. -
Test django application: need to delete a row in postgres, and then recover
I have a Django application which is interacting with postgres. To test application I want to delete several rows from a table and see the outcome of it on the retrieved data (queries are pretty complex, so to just see whether everything is good is hard otherwise). Whats the best practice to approach such a case? Most straightforward is to write down all of the data for the deleted rows, delete rows, test app, then reinsert the rows, but I feel like its too manual, time consuming and not how it should be done. Besides there is a small chance of missing something out and/or sometimes the model can't be easily deleted without deleting other model rows when they are related by a foreign key. -
Running Daphne with DotEnv in a systemd process
I'm using a .env file which contains the configuration for my Django app. I have a systemd service which runs Daphne (similar to what's below) [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/django/myproject/src ExecStart=/home/django/myproject/venv/bin/python /home/django/myproject/venv/bin/daphne -e ssl:8001:privateKey=/etc/letsencrypt/live/myproject.com/privkey.pem:certKey=/etc/letsencrypt/live/myproject.com/fullchain.pem myproject.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target Moreover, I'm using gunicorn through a similar mechanism, which works perfect. However, Daphne does not. When I run it through systemctl start daphne.service, it tells me that Django settings are improperly configured So, I tried setting the dotenv in the asgi.py file like so: dotenv.load_dotenv( os.path.join(os.path.dirname(__file__), '.env' )) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.dev') if os.getenv('DJANGO_SETTINGS_MODULE`): os.environ['DJANGO_SETTINGS_MODULE'] = os.getenv('DJANGO_SETTINGS_MODULE') But this just gives me the same error. Any ideas how to fix this? I checked out this response, but it seems ridiculous/redundant to set the environment variables in daphne.service. -
Download a few files in Django without zip
I want to download multiple files in Django without creating zip acrhive. I have a valid which uses zip (create 1 zip file and download it) But I have to implement downloading several files without zip archive creating. How can I modify my code? class DashboardDownloadDocumentsView(GenericAPIView): permission_classes = (IsAuthenticatedManager,) serializer_class = DashboardDocumentDownloadSerializer def get(self, request, *args, **kwargs): """ Get zipped archive file with photo """ document_type = kwargs.get("document_type", None) user_id = kwargs.get("user_id", None) try: user = User.objects.get(id=user_id) except User.DoesNotExist: raise NotFound("This is user not found.") if document_type == 'vehicle_photo': user_vehicle = user.vehicle.select_related().first() documents = user_vehicle.photos.all() else: documents = user.document_owner.select_related().filter(document_type=document_type) # without creation file in_memory = BytesIO() zip_filename = f"{document_type}_{user_id}.zip" zip_archive = ZipFile(in_memory, "w") # Writing all files in our zip archive for document in documents: f_dir, f_name = os.path.split(document.photo.url if document_type == "vehicle_photo" else document.file.url) zip_path = f"{settings.ROOT_DIR}{f_dir}" zip_archive.write(zip_path+"/"+f_name, f_name) # Save zip file zip_archive.close() response = HttpResponse(content_type="application/zip") response['Content-Disposition'] = f'attachment; filename={zip_filename}' in_memory.seek(0) response.write(in_memory.read()) return response -
How to debug: ConnectionResetError: [Errno 54] Connection reset by peer
I am now trying to debug this error in django for ages. Is someone able to help me? The reason for this error is that I am doing a successful ajax call, however, then at the end the error is thrown. Please see: Exception happened during processing of request from ('127.0.0.1', 59734) Traceback (most recent call last): File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/socketserver.py", line 720, in __init__ self.handle() File "4_Code/Floq_Django/venv/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "Floq_Django/venv/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer Thank you so much. -
foreign key to Postgres view on Django
I have Django model handling a Postgres view, the definition is something like this: class ViewModel(models.Model): some_field = models.CharField() class Meta: managed = False db_table = "view_name" I want to have a relation in another model (which represents a table in the database) to this ViewModel. class AnotherModel(models.Model): view_attribute = models.ForeignKey(ViewModel) When I try to run the migration to create this foreign key I get the error: django.db.utils.ProgrammingError: referenced relation "view_name" is not a table Is there anyway around this error? -
How to solve XLRD error on excel upload to a model
This is the error I get from a view that tries to upload an excel data file into a django model. Traceback (most recent call last): File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python\Django\Links Online Exams\Links_Online_Results\teachers\views.py", line 106, in UploadTeacherView book = xlrd.open_workbook(path) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\xlrd\__init__.py", line 172, in open_workbook bk = open_workbook_xls( File "D:\Python\Django\Links Online Exams\env\lib\site-packages\xlrd\book.py", line 79, in open_workbook_xls biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\xlrd\book.py", line 1284, in getbof bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8]) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\xlrd\book.py", line 1278, in bof_error raise XLRDError('Unsupported format, or corrupt file: ' + msg) xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'code,fir' [05/Apr/2021 22:54:31] "POST /teachers/upload HTTP/1.1" 500 87102 Below is the view that am trying to work out from. I have actually been unable to figure out the right solution to this problem. I believe one of us must have caught this error in one or more instances. def UploadTeacherView(request): message='' if request.method == 'POST': form = NewTeachersForm(request.POST, request.FILES) if form.is_valid(): excel_file = request.FILES['file'] fd, path = tempfile.mkstemp() try: with os.fdopen(fd, 'wb') as tmp: tmp.write(excel_file.read()) … -
I want to get all anime related to specific Genre,
model class Genre(models.Model): genre = models.CharField(max_length=100, null=True) def __str__(self): return self.genre class anime(models.Model): anime_name = models.CharField(max_length=100, default="") description = models.CharField(max_length=1000, null=True) Genre = models.ManyToManyField(Genre) Season = models.IntegerField(null=True) Episodes = models.CharField(max_length=100,null=True) IMDB_Rating = models.FloatField(null=True) #Image = def __str__(self): return self.anime_name view def g(request, G): animes = anime.objects.filter(Genre=G) x = {'animes': animes} return render(request, 'Anime/genre.html', x) urls path('genre/<G>/', views.g, name="main"),` -
Python API to Generate Mask Number
I am working on a web app. This web app need a voice call features. When a client click on the Call Button then a call will be connect with the receiver. Call Here receiver is a registered user. But I need to keep private the contact number of the user. I have to ensure that from the web app i.e. site, when a client make call, client or caller will not be able to see the original phone number of the receiver i.e. I need to do Call Masking. For that reason I am looking for an API to generate a Mask Number. When a new user will sign up into the site then a mask number will be generate for that user using the original number of that user by the API. My Web app is python (django) based. So is there are any API available in Python for call Making. -
Problem not display datetime field form in browser in django
What I can't see input datetime form.form django in my browser? the program that I run in the browser, The following code displayed instead of the input datetime i have brought the codes of all the pages, please check Thank you for your reply forms.py from django import forms from django.contrib.auth.models import User from datetime import datetime class ExpenseForm (forms.Form): text = forms.CharField( widget=forms.TextInput(attrs={'placeholder':'توضیحات' ,'class':'form-control'}), label='توضیحات', ) date = forms.DateTimeField( initial=datetime.now(), widget=forms.DateTimeInput(attrs={ 'placeholder':'تاریخ' , 'class':'form-control', 'type': 'datetime-local'}), label='تاریخ', ) amount = forms.IntegerField( widget=forms.NumberInput(attrs={'placeholder':'مقدار' ,'class':'form-control'}), label='مقدار' ) view.py @login_required() def submit_expense(request): expense_form = ExpenseForm(request.POST or None) if expense_form.is_valid(): text = expense_form.cleaned_data.get('text') date = expense_form.cleaned_data.get('date') amount = expense_form.cleaned_data.get('amount') Expense.objects.create(text=text , date=date , amount=amount , user_id=request.user.id) return redirect('/submit/expense') context ={ 'expense_form':expense_form } return render(request,'hello.html',context) hello.html {% extends 'shared/_MainLayout.html' %} {% load static %} {% block content %} <div class="login-form"><!--expense form--> <div class="col-sm-4 col-sm-offset-1"> <div class="login-form"><!--expense form--> <h2>پولهای خرج شده :</h2> <form method="post" action="#"> {% csrf_token %} {{ expense_form.text }} {{ expense_form.amount }} {{ expense_form.data }} <button type="submit" class="btn btn-default">ثبت</button> </form> </div><!--/login form--> </div> {% endblock %} please check the image to see my problem browser page -
Django make migrations returns ModuleNotFoundError
I'm just starting to learn Django through online lectures and I'm trying to run this command python3 manage.py makemigrations It returns the following error Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/base.py", line 368, in execute self.check() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/urls/resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", … -
Uncaught SyntaxError: missing ) after argument list at line 1
I get the error down below at line one. Uncaught SyntaxError: missing ) after argument list {% extends 'main/base.html' %} {% load static %} {% block title %} Decont {% endblock title %} {% block meta %} <script> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); $(document).ready(function () { // Decont Lista // const URL_DECONT = "/api/decont-list/"; let decont_lista = []; $.getJSON(URL_DECONT, function(result){ $.each(result, function(i, field){ decont_lista.push(field); }); function compare(a, b) { if (a.data < b.data) { return 1; } if (a.data > b.data) { return -1; } return 0; } decont_lista.sort(compare); $.each(decont_lista, function(i, field){ $("#table_decont").append(` <tr> <th class="align-middle text-center" scope="row">${field.pk}</th> <td class="align-middle text-center">${field.user}</td> <td class="align-middle text-center">${field.data}</td> <td class="align-middle text-center"><a id="atasament_nume${field.pk}" href='${(field.file!==null)?field.file:"#"}' style="color: black; font-weight: 500;">${(field.file_name!==null)?field.file_name:"Fără atașament"}</a></td> <td class="align-middle text-center"> <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapse${field.pk}" aria-expanded="false" aria-controls="collapse${field.pk}"> Edit </button> </td> </tr> <tr> <td colspan="7" style="padding: 0 !important;"> <div …