Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending emails via gmail is too slow - Django
I'm using the below to connect to gmail server to send emails. EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'password' The email is working perfectly fine, but it takes around 20 - 30 secs for the process to complete. I know many are facing this issue, but I didn't find a proper answer for this. -
Django Json Response - Problems at showing count fields
I'm having problems to show my fields correctly to a JSON. This is the view function query = "SELECT sede.id, sede.Nombre as nombre, count(distinct(mesa.id)) as 'mesas' , count(distinct(plan.id)) as planes, count(distinct(diagnostico.id)) as diagnosticos FROM ubicacion_sede sede join ubicacion_subregion subregion on subregion.Sede_id = sede.id join ubicacion_region region on region.id = subregion.Region_id join ubicacion_pais pais on pais.id = region.Pais_id join comunidades_comunidad comunidad on comunidad.Subregion_id = subregion.id join comunidades_mesa mesa on mesa.Comunidad_id = comunidad.id and mesa.Estado = 'Activo' left join comunidades_planesdeaccion plan on plan.Mesa_id = mesa.id left join comunidades_diagnostico diagnostico on diagnostico.Mesa_id = mesa.id group by sede.id, sede.Nombre" respuesta = Sede.objects.raw(query) respuesta_serialized = serializers.serialize('json', respuesta, fields=('nombre', 'mesas', 'planes', 'diagnosticos')) content = JsonResponse(respuesta_serialized, safe=False) and this is the JSON I get from this "[{\"model\": \"ubicacion.sede\", \"pk\": 1, \"fields\": {}}, {\"model\": \"ubicacion.sede\", \"pk\": 2, \"fields\": {}}, {\"model\": \"ubicacion.sede\", \"pk\": 6, \"fields\": {}}, {\"model\": \"ubicacion.sede\", \"pk\": 12, \"fields\": {}}, {\"model\": \"ubicacion.sede\", \"pk\": 22, \"fields\": {}}]" Here I have two problems Why i'm not getting the files i want Why I get the JSON formatted like \" and not " Thanks in advance for your answer, I've been turning SOF upside down but couldn't get the solution -
How to update Chart JS without refreshing using ajax in Django
I wanna update variable for display in chart js without refreshing using ajax. The both variable will sent from view.py graph.html <html> <div class="top5"> <p class="topicTop5">Top 5 Selling Products</p> <canvas id="top5"></canvas> </div> <script> setInterval(function() { $.ajax({ type: "GET", url: "{% url 'updateData' %}" }) .done(function(response) { // how to coding for update variable in chart // update {{top5StockC|safe}} (response.top5StockC) and {{top5Quan|safe}} (response.top5Quan) }); }, 5000) </script> <script> // top5 of product best seller var top5 = document.getElementById('top5').getContext('2d'); var chart = new Chart(top5, { type: 'horizontalBar', data: { labels: {{top5StockC|safe}}, // need to update variable datasets: [{ label: 'quantity of products', backgroundColor: '#CE3B21', borderColor: 'rgb(255, 99, 132)', data: {{top5Quan|safe}} // need to update variable }] }, .... </script> <html> Thank for your answering -
Django - Unable to remain in the view assigned to LOGIN_REDIRECT_URL after redirecting to back page. I'm using custom AUTH_USER_MODEL
I'm trying to get a custom user model named (UserAccount) working for logging in and logging out My custom user account inherits these two classes UserAccount(AbstractBaseUser, PermissionsMixin) Used django.contrib.auth.views - LoginView and LogoutView in accounts app's urls.py file: from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name="accounts/login.html"), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name="accounts/logout.html"), name='logout'), path('signup/', views.signup, name='signup'), ] When I login, as per the setting LOGIN_REDIRECT_URL, I'm able to get redirected to the landing_page. AUTH_USER_MODEL = 'accounts.UserAccount' LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'landing_page' LOGIN_REQUIRED_IGNORE_VIEW_NAMES = [ 'login', 'logout', 'signup', ] I've used the django-login-required-middleware and also included these two in my settings file: INSTALLED_APPS = [ 'login_required', # along with others ] MIDDLEWARE = [ 'login_required.middleware.LoginRequiredMiddleware', # along with others ] But whenever I hit back button on the browser, it is again taking me back to login page, even after logging in. Can someone please help resolve this authentication issue? -
How to auto-fill and display data in Django from fields of User model to another model from a different app?
I'm new in Django and right now I'm working to a payment application project for registered users and for non-registered users. My User model has some required fields from the paper invoice like below: #users/models.py class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=100, blank=False, null=False) phone = models.CharField(max_length=11, blank=False, null=False) clientid = models.IntegerField(blank=True, null=False, unique=True) Notice that the authentication process is based on e-mail address and the required field from the invoice payment is "clientid, phone, name". The other app called payments has 1 model class for non-registered users and for authenticated users like below: #payments/models.py class Payment(models.Model): invoiceid = models.IntegerField(blank=False, null=False) name = models.CharField(max_length=50, blank=False, null=False) amount = models.DecimalField(decimal_places=2, max_digits=20) email = models.EmailField(max_length=255, blank=False, null=False) phone = models.CharField(max_length=11, blank=False, null=False) clientid = models.IntegerField(blank=True, null=False, unique=False) For both models I'm using crispy forms, for non-registered users is quite easy to make the payment if they fill all the fields. (different templates are used for this actions). What I want to achieve is when the user is registered and wants to make a payment, the fields like "name, phone and clientid should be filled automatically and displayed to the user in read mode only based on the registration user table. … -
admin site list vs tuple django
when customizing admin site we can use list or tuple like @admin.register(Model_name) class Model_nameAdmin(admin.ModelAdmin): list_display = ['a', 'b', 'c'] # using list # lets say a, b, c are fields of model(Model_name) or list_display = ('a', 'b', 'c') # using tuple I'm curious Is there any difference using a list over tuple or vice-versa like performance while retrieving the admin site or something like that. I know tuples are better than lists for performance but we aren't looping here. I've looked at whats-the-difference-between-lists-and-tuples, why-does-django-use-tuples-for-settings-and-not-lists, why-djangos-modeladmin-uses-lists-over-tuples-and-vice-versa, but didn't get my answer. Is it better to use tuple all the time? I'm asking specifically for the admin site. -
comment system in class based view in django showing error
the basic source files are here and i am trying to do it in class based view for further upgrade. My main project is written in class based view and it will be easy to integrate for me. views.py codes are give below: from .models import Post,Comment from .forms import CommentForm from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView,DetailView from django.shortcuts import redirect,render, get_object_or_404 from django.http import HttpResponseRedirect class PostList(ListView): model=Post template_name='home.html' context_object_name='post_list' queryset=Post.objects.all() class PostDetail(DetailView): model=Post def get_queryset(self): queryset = super(PostDetail, self).get_queryset() post=Post.objects.all() comments=Comment.objects.filter(post=post) return queryset def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) if request.method == "POST": comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): comment=comment_form.save(commit=False) comment.post=post comment.save() else: comment_form = CommentForm() context['post']=post.objects.all() context['comments']=comments.objects.all() context['comment_form']=comment_form() template_name='Post_detail.html' return render(request, template_name, context) when i execute the runserver it shows NameError at /post/1/ name 'request' is not defined the models.py is: from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') content = models.TextField() def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) body = models.TextField() reply=models.ForeignKey('Comment',on_delete=models.CASCADE,null=True) def __str__(self): return self.name the function base view was: def PostDetail(request,pk): post = get_object_or_404(Post, pk=pk) comments=Comment.objects.filter(post=post) if request.method == "POST": comment_form = CommentForm(request.POST … -
Reset many to many fields from model
I want to reset all upvotes from all my Posts with django-orm, don`t know how to write query for that and apply it to the view. Also, maybe it would be better to make separate upvote model than just a field in the Post. class Post(models.Model): author = models.ForeignKey( User, related_name='posts', on_delete=models.SET_NULL, null=True ) title = models.CharField(max_length=100) creation_date = models.DateTimeField(auto_now_add=True) link = models.URLField() upvotes = models.ManyToManyField(User, related_name='upvotes', blank=True) -
django authentication via email using mysql database
i tried alot to solve my problem but i cant code works fine i guess but it never finds similar rows in database or i cant login .. i copied the email backend from some site i havent written it by my own so i cant find errors in it if there are cause am learning python web development. views.py from django.shortcuts import render from django.contrib.auth import authenticate from Play.models import user from django.contrib.auth.models import User from django.contrib.auth.models import auth from django.shortcuts import redirect from django.shortcuts import HttpResponse from django.contrib.auth.hashers import make_password def JoinRequest(request): if request.method == 'POST': fullname = request.POST['fullname'] email = request.POST['email'] phone = request.POST['phone'] password = request.POST['password'] cpassword = request.POST['cpassword'] #encpass = make_password(password) def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') return ip if password != cpassword: return HttpResponse('Password Not Matching To Confirm Password Value..') else: senddata = user(fullname=fullname, email=email, phone=phone, password=password , ipaddress=get_client_ip(request)) senddata.save() return HttpResponse('') def Join_View(request): return render(request, 'Join.html', {}) def login_view(request): return render(request, 'Login.html', {}) def LoginREQUEST(request): if request.method == 'POST': username = request.POST['email'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponse('DONE') else: return HttpResponse("NONE") SETTINGS.py AUTHENTICATION_BACKENDS = [ … -
How can I install psycops2 in my virtual env?
I need to install psycopg2 for connecting postgresql with django.I have tried this command. pip install psycopg2 but this message was shown: Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\Rafid\AppData\Local\Temp\pip-install-oknhhl43\psycopg2\ I am new to web development so a detailed solution will be helpful...Thanks in advance -
how to add a modelform to modelformset_factory
With respect to these models: class Projects(models.Model): projectDescription = models.CharField(max_length=50,blank=True,null = True,) status = models.IntegerField(choices = Status_CHOICES, default = 4) projectOwner = models.ForeignKey(staff, on_delete=models.CASCADE, blank=True,null = True,) class Updates(models.Model): project = models.ForeignKey(Projects, on_delete=models.CASCADE) update = models.CharField(max_length=50,blank=True,null = True,) updateDate = models.DateTimeField(default = timezone.now, editable = False) addedBy = models.CharField(max_length=35,blank=True,) I want to create a view that displays forms for all of the current projects. This is easy using a modelformset_factory. But how can I also add an additional form to each of these instances to make an Update to the project (foreign key)? What I have below seems to be very close, but it is saving an update to each project with the value of whatever I typed into the last form. help! additional form class updateForm(ModelForm): def __init__(self, *args, **kwargs):# for ensuring fields are not left empty super(updateForm, self).__init__(*args, **kwargs) class Meta: model = Updates fields = ('update',) view: def MDSprojects(request): projects = Projects.objects.filter(dept = 'Assistive Technology') projectFormset = modelformset_factory(Projects, form=EditProjectForm, extra = 0) if request.method == 'POST': formsetA = projectFormset(request.POST,request.FILES) if formsetA.is_valid(): for f in formsetA: formA = f.save(commit = False) id = formA.id formA.save() formsetB = updateForm(request.POST,request.FILES) if formsetB.is_valid(): formB = formsetB.save(commit = False) project = Projects.objects.get(id … -
Getting the info of particular entry from database on clicking the button using django
I am making django webapp it has a page where name and image of all registered doctors are there in a card.The card has a button to show the info of them. How can I get the data for that particular doctor on whose card's button is clicked from the databse. -
python-m doesn't found .django installation on pydroid3 issue
Since I had already installed django 3.0.6 in my pydroid3 but still it does not allow me to create project. again installing django it says python-m not found what exactly is python-m is i need to installed it? -
when i'm try to install kivy on my windows 10 it's give me error my python version is 3.8.3
ERROR: Command errored out with exit status 1: command: 'C:\Windows\System32\kivy_venv\Scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Manish Chauhan\AppData\Local\Temp\pip-install-ay9lfij5\kivy\setup.py'"'"'; file='"'"'C:\Users\Manish Chauhan\AppData\Local\Temp\pip-install-ay9lfij5\kivy\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Manish Chauhan\AppData\Local\Temp\pip-pip-egg-info-jnvkq4lz' cwd: C:\Users\Manish Chauhan\AppData\Local\Temp\pip-install-ay9lfij5\kivy\ Complete output (394 lines): ERROR: Command errored out with exit status 1: command: 'C:\Windows\System32\kivy_venv\Scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Manish Chauhan\AppData\Local\Temp\pip-wheel-3zpe7pyc\cython\setup.py'"'"'; file='"'"'C:\Users\Manish Chauhan\AppData\Local\Temp\pip-wheel-3zpe7pyc\cython\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Manish Chauhan\AppData\Local\Temp\pip-wheel-cqe19b66' cwd: C:\Users\Manish Chauhan\AppData\Local\Temp\pip-wheel-3zpe7pyc\cython\ Complete output (321 lines): Unable to find pgen, not compiling formal grammar. running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.8 copying cython.py -> build\lib.win-amd64-3.8 creating build\lib.win-amd64-3.8\Cython copying Cython\CodeWriter.py -> build\lib.win-amd64-3.8\Cython copying Cython\Coverage.py -> build\lib.win-amd64-3.8\Cython copying Cython\Debugging.py -> build\lib.win-amd64-3.8\Cython copying Cython\Shadow.py -> build\lib.win-amd64-3.8\Cython copying Cython\StringIOTree.py -> build\lib.win-amd64-3.8\Cython copying Cython\TestUtils.py -> build\lib.win-amd64-3.8\Cython copying Cython\Utils.py -> build\lib.win-amd64-3.8\Cython copying Cython__init__.py -> build\lib.win-amd64-3.8\Cython creating build\lib.win-amd64-3.8\Cython\Build copying Cython\Build\BuildExecutable.py -> build\lib.win-amd64-3.8\Cython\Build copying Cython\Build\Cythonize.py -> build\lib.win-amd64-3.8\Cython\Build copying Cython\Build\Dependencies.py -> build\lib.win-amd64-3.8\Cython\Build copying Cython\Build\Distutils.py -> build\lib.win-amd64-3.8\Cython\Build copying Cython\Build\Inline.py -> build\lib.win-amd64-3.8\Cython\Build copying Cython\Build\IpythonMagic.py -> build\lib.win-amd64-3.8\Cython\Build copying Cython\Build__init__.py -> build\lib.win-amd64-3.8\Cython\Build creating build\lib.win-amd64-3.8\Cython\Compiler copying Cython\Compiler\AnalysedTreeTransforms.py -> build\lib.win-amd64-3.8\Cython\Compiler copying Cython\Compiler\Annotate.py -> build\lib.win-amd64-3.8\Cython\Compiler copying Cython\Compiler\AutoDocTransforms.py -> build\lib.win-amd64-3.8\Cython\Compiler copying Cython\Compiler\Buffer.py -> build\lib.win-amd64-3.8\Cython\Compiler copying Cython\Compiler\Builtin.py -> build\lib.win-amd64-3.8\Cython\Compiler copying Cython\Compiler\CmdLine.py -> build\lib.win-amd64-3.8\Cython\Compiler copying Cython\Compiler\Code.py -> build\lib.win-amd64-3.8\Cython\Compiler copying Cython\Compiler\CodeGeneration.py -> build\lib.win-amd64-3.8\Cython\Compiler copying Cython\Compiler\CythonScope.py -> build\lib.win-amd64-3.8\Cython\Compiler copying … -
Heroku gunicorn deployment ModuleNotFoundError: No module named APP_NAME
I am trying to deploy a django app to heroku and I keep receiving 2020-06-07T13:43:58.422709+00:00 heroku[web.1]: State changed from crashed to starting 2020-06-07T13:44:02.573617+00:00 heroku[web.1]: Starting process with command `gunicorn --pythonpath frolicaide frolicaide.wsgi` 2020-06-07T13:44:04.912297+00:00 heroku[web.1]: Process exited with status 3 2020-06-07T13:44:04.953057+00:00 heroku[web.1]: State changed from starting to crashed 2020-06-07T13:44:04.706207+00:00 app[web.1]: [2020-06-07 13:44:04 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-06-07T13:44:04.706710+00:00 app[web.1]: [2020-06-07 13:44:04 +0000] [4] [INFO] Listening at: http://0.0.0.0:4939 (4) 2020-06-07T13:44:04.706805+00:00 app[web.1]: [2020-06-07 13:44:04 +0000] [4] [INFO] Using worker: sync 2020-06-07T13:44:04.710715+00:00 app[web.1]: [2020-06-07 13:44:04 +0000] [10] [INFO] Booting worker with pid: 10 2020-06-07T13:44:04.715576+00:00 app[web.1]: [2020-06-07 13:44:04 +0000] [10] [ERROR] Exception in worker process 2020-06-07T13:44:04.715577+00:00 app[web.1]: Traceback (most recent call last): 2020-06-07T13:44:04.715593+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-06-07T13:44:04.715593+00:00 app[web.1]: worker.init_process() 2020-06-07T13:44:04.715593+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-06-07T13:44:04.715594+00:00 app[web.1]: self.load_wsgi() 2020-06-07T13:44:04.715594+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-06-07T13:44:04.715594+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-06-07T13:44:04.715594+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-06-07T13:44:04.715594+00:00 app[web.1]: self.callable = self.load() 2020-06-07T13:44:04.715595+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-06-07T13:44:04.715595+00:00 app[web.1]: return self.load_wsgiapp() 2020-06-07T13:44:04.715595+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-06-07T13:44:04.715595+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-06-07T13:44:04.715595+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app 2020-06-07T13:44:04.715596+00:00 app[web.1]: mod = importlib.import_module(module) 2020-06-07T13:44:04.715596+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in … -
Blacklist the token once there is a changes in role or permission in django rest framework simple-jwt
I would like to blacklist the token (and redirect to login page) once there is a changes in role or permission of a specific user. The admin only can change the role. If any point of time, the role and permission changed it should automatically blacklist the token. I mean there will be a function of blacklist token, if any changes detected that function should execute automatically. Note : user does't have any idea about his role change or not. There will be mechanism that will detect automatically the changes and execute the blacklist method to blacklist the token and redirect to login page. Any inputs would be really appreciated. -
Suggestions on implementing search with Django and Python
I've been venturing recently into python and django, and was looking to build a website that displays information retrieved from a dataset, very similar to this website - https://art-explorer.azurewebsites.net/. This is just a project to develop my skills, and will not necessarily be deployed live. The database currently has a thousands of rows that display information about objects, including tags, metadata, and URLs of images. My goal was to implement a search engine that goes through all of the images linked in the dataset and displays them with some kind of metadata information, such as author, year, title, etc. The user should have the option to filter through these images by selecting tags, specific years, authors or just search by keywords. I already have the basic structure of the website implemented in Django, including the HTML and CSS, and was thinking on using SQLite for the database. I'm pretty new to this, so this may not be the best implementation or even feasible. Do you think this is doable with the current structure I'm going for, is there a better way to implement this in a way that it will be more efficient in the backend? Thanks! -
Django admin users table
everyone! I have a simple django application using sqlite database, in which I created superuser. Now on admin page I can see that there is a users table. The problem is that I can't find this table in my database. There is actually auth_user table but im not sure it's the same table that admin page shows. -
How to render celery results in Django pages
I want to display celery results on rendered pages in Django. Please suggest any library, git link, or code for the same. -
Lost in space for paytm integration in django
how to solve this lost in space error. what is the reason for this error? what is the use of the transaction status URL? what should be the action parameter in form pay.html? how does this work? I am stuck with this error from morning please help me to solve this. thank you in advance. pay.html <head> <title>Payment Home</title> </head> <body> <h2>Payment Home</h2> {% if error %} <h3>{{ error }}</h3> {% endif %} <form action="https://securegw.paytm.in/order/process" method="POST"> {% csrf_token %} Join Club: {{user.username}}<br> <label for="amount">Amount: </label> 500<br> <input type="submit" name="submit" value="Submit" required> </form> </body> </html> views.py @login_required def initiate_payment(request): if request.method == 'GET': return render(request,'pay.html') transaction = Transaction.objects.create(made_by=request.user, amount=500) transaction.save() merchant_key = 'R6xrODspE8O!_7I5' params = ( ('MID', '*****************'), ('ORDER_ID', str(transaction.order_id)), ('CUST_ID', str(transaction.made_by.email)), ('TXN_AMOUNT', str(transaction.amount)), ('CHANNEL_ID', 'WEB'), ('WEBSITE', 'DEFAULT'), # ('EMAIL', request.user.email), # ('MOBILE_N0', '9911223388'), ('INDUSTRY_TYPE_ID', 'Retail'), ('CALLBACK_URL', 'https://presimax.online/callback'), ('PAYMENT_MODE_ONLY', 'YES'), ) paytm_params = dict(params) checksum = generate_checksum(paytm_params, merchant_key) transaction.checksum = checksum transaction.save() paytm_params['CHECKSUMHASH'] = checksum print('SENT: ', checksum) return render(request, 'redirect.html', context=paytm_params) @csrf_exempt def callback(request): if request.method == 'POST': received_data = dict(request.POST) paytm_params = {} paytm_checksum = received_data['CHECKSUMHASH'][0] for key, value in received_data.items(): if key == 'CHECKSUMHASH': paytm_checksum = value[0] else: paytm_params[key] = str(value[0]) # Verify checksum is_valid_checksum = verify_checksum(paytm_params, 'R6xrODspE8O!_7I5', … -
Django / Vuetify - @mdi/fonts not found
Tried to integrated vuetify to Django, yeah everything work fine excerpt @mdi/fonts not found. the error show <b>http://localhost:8000/static/dist/fonts/materialdesignicons-webfont.woff</b> Yeah i know if i prepend static to the link everything will be okay, for example <b>http://localhost:8000/static/static/dist/fonts/materialdesignicons-webfont.woff </b> But i dont know where to config it. My index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Django</title> <link rel="stylesheet" href="{% static 'static/dist/app.css' %}" /> </head> <body> <div id="app"> <App></App> </div> <script src="{% static 'static/dist/app.js' %}"></script> </body> </html> in Webpack.config.js const path = require("path"); const VueLoaderPlugin = require("vue-loader/lib/plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); module.exports = { mode: "development", entry: ["./frontend/src/app.js", "./frontend/src/app.scss"], output: { path: path.resolve(__dirname, "./static/dist"), filename: "app.js", }, module: { rules: [ // ... other rules { test: /\.vue$/, loader: "vue-loader", }, { test: /\.s(c|a)ss$/, use: [ "vue-style-loader", "css-loader", { loader: "sass-loader", // Requires sass-loader@^7.0.0 options: { implementation: require("sass"), fiber: require("fibers"), indentedSyntax: true, // optional }, // Requires sass-loader@^8.0.0 options: { implementation: require("sass"), sassOptions: { fiber: require("fibers"), indentedSyntax: true, // optional }, }, }, ], }, { test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/, use: [ { loader: "file-loader", options: { name: "[name].[ext]", outputPath: "fonts/", }, }, ], }, { test: /\.css$/, use: … -
GEOS_ERROR: ParseException: Unknown WKB type 337
I am coding a geo-based application with geodjango and postgis. I wrote the model and filled the first few points by hand from the admin interface. All worked fine, and I can even search by the nearest points. So the model and database are all working fine. Now I am trying to bulk filling the database from a script. Based on the answers I found here I am doing it first filling the longitude and the latitude columns then by executing engine.execute("UPDATE listings_listing SET location = ST_SetSRID(ST_MakePoint(longitude,latitude), 4326)") from a python script. The query executes without exceptions and the database seems filled with proper values. Here few examples longitude, latitude, location -55.7385809,-34.7413717,"0101000020E6100000A279A5D189DE4BC008D79244E55E41C0" -56.1645314,-34.9011127,"0101000020E610000022156B5D0F154CC0504134A9577341C0" -56.4670779,-30.4264621,"0101000020E610000099976835C93B4CC0C57BC49E2C6D3EC0" -55.760207,-34.774156,"0101000020E61000005B9885764EE14BC04700378B176341C0" -56.2553815,-34.7901883,"0101000020E610000070404B57B0204CC04617E5E3246541C0" -55.760336,-34.773944,"0101000020E610000059FCA6B052E14BC0BC77D498106341C0" -57.0544726,-30.7552116,"0101000020E610000098C349F5F8864CC0518F238C55C13EC0" -56.4739006,-30.4097107,"0101000020E610000003475DC6A83C4CC03F52E9CCE2683EC0" Now when I try to make the first search by the nearest points i get GEOS_ERROR: ParseException: Unknown WKB type 337 and from the logs of django Error encountered checking Geometry returned from GEOS C function "GEOSWKBReader_read_r". I googled the error but nothing. I checked possible NULL values in longitude and latitudes, but they are all fine. I suspect that I am missing a step. Someone can point me in the right direction? -
how to generate unique id in factory using faker: Django
I am trying to insert data into my database (sqlLite3) using factory and faker. This is my model: class User(models.Model): id = models.CharField(max_length=9, primary_key=True) real_name = models.CharField(max_length=200) tz = models.CharField(max_length=200) Factory for the model: class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User fake.add_provider(MyProvider) real_name = factory.Faker('name') id = ''.join(fake.random_letters(length=9)).upper() tz = fake.timezone() When I run UserFactory.create() for the first time, User is added but when I run the second time in the same python shell or try to run UserFactory.create_batch(5), it gives me the following error: django.db.utils.IntegrityError: UNIQUE constraint failed: activities_user.id If I run it in a different terminal or exit from shell and run the same command again it runs fine. Seems ''.join(fake.random_letters(length=9)).upper() always returns same value. Even though I have used random_letters I wonder why this is happening. I am new to using factory boy and faker. Please help me out on this. Let me know if I am missing anything. -
Django calling methods of DetailView and RedirectView in template
I'm trying to get into Django and got stuck with DeatailView and RedirectView I made the following template for rendering posts with enabling post detailed view and like button. When I click on either Like or Detail button none of the requests is sent. I tried changing different methods, but that didn't help either. I trying to get whether I was mistaken in the template or in view logic. {% extends 'base.html' %} {% block content %} {% for post in object_list %} <div class="card" style="width: 40rem;"> <img src = "{{ post.image.url }}" style="height: 40rem;"> <div class="card-body"> <h5 class="card-tittle">{{post.author.username}}</h5> <p class="card-text">{{ post.description }}</p> <p class="card-text">Likes : {{ post.likes.count }}</p> <p class="id">Post_id: {{ post.id }}</p> <div class="btn-group-vertical"> {% if user.is_authenticated %} <form action="{% url 'like_post' %}" method="POST"> {% csrf_token %} <button type="button" class="btn btn-secondary">Like</button> </form> {% endif %} <form action="{% url 'detail' pk=post.id %}" method="GET"> <button type="button" class="btn btn-secondary">Detail</button> </form> <!-- <button type="button" class="btn btn-secondary">down</button> --> </div> </div> </div> {% endfor %} {% endblock %} Posts views.py file class PostDetail(DetailView): model = Post def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) print(context.items()) return context class PostLikeUpvote(RedirectView): def get_redirect_url(self, *args, **kwargs): post_id = kwargs.get('id') post = get_object_or_404(Post, id=post_id) user = self.request.user if … -
keras image_load() in Django expected str, bytes or os.PathLike object, not ImageFieldFile
I got this error expected str, bytes or os.PathLike object, not ImageFieldFile when i want load the image using image_load().Here is my Code from django.db import models from keras.preprocessing.image import load_img, img_to_array from keras.preprocessing import image import numpy as np # Create your models here. class Image(models.Model): picture = models.ImageField(upload_to='article_images') classified = models.CharField(max_length=200, blank=True) uploaded = models.DateTimeField(auto_now_add=True) def __str__(self): return self.classified def save(self, *args, **kwargs): img = load_img(self.picture, target_size=(224, 224)) img_arr = img_to_array(img) to_pred = np.expand_dims(img_arr, axis=0) # (1,299,299,3) print(to_pred.shape) super().save(*args, **kwargs) error : expected str, bytes or os.PathLike object, not ImageFieldFile