Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Password Reset Email Not Being Sent in Django
First of all, I'd just like to clarify that I've looked at all the other questions in regard to this on Stack Overflow and I haven't been able to resolve the issue. So, the issue I'm having is that I'm not receiving a password reset email on my site, even though everything indicates that the email has been sent. I say this because I get the confirmation on my screen that the email has been sent and I also get the email displayed in the console (see below). Here are my email settings: EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" EMAIL_USE_TLS = True EMAIL_HOST = "localhost" EMAIL_PORT = 25 EMAIL_HOST_USER = os.environ.get("EMAIL_ADDRESS") EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_PASSWORD") Here are my password reset URLs: from django.conf.urls import url from django.core.urlresolvers import reverse_lazy from accounts.views import change_password from django.contrib.auth.views import ( password_reset, password_reset_done, password_reset_confirm, password_reset_complete) urlpatterns = [ url(r'^$', password_reset, name='password_reset'), url(r'^reset-password/done/$', password_reset_done, name='password_reset_done'), url(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', password_reset_confirm, name='password_reset_confirm'), url(r'^complete/$', password_reset_complete, name='password_reset_complete'), url(r'^change-password/$', change_password, name='change_password'), ] Any feedback is greatly appreciated! Thanks in advance. -
How to get 4th child items from an xml in python
I have an xml file. It has invoice informations. I'm trying to save them to my mysql database. First I'm getting invoice's header informations and save them to a django model. Then trying to get the product part. But I coldn't get it done. here is my sample xml <SIPARISLER> <SIPARIS> <SIPARIS_NO>YT3949031</SIPARIS_NO> <PAZARYERI_KARGOKODU/> <CariHesapKodu>YT2099</CariHesapKodu> <CariHesapOzelKodu>YT</CariHesapOzelKodu> <POSTA>ayse@icir.com</POSTA> <TARIH>2016-06-28</TARIH> <sipariszaman>08:56:58</sipariszaman> <ISKONTO>0</ISKONTO> <NET_TOPLAM>62.33</NET_TOPLAM> <TeslimAlici>Ayydın</TeslimAlici> <TeslimAdresi>Arvat Atayolu Cad. ÖztaşrnLogipark a - anbul</TeslimAdresi> <TeslimTelefon>0506-0624914</TeslimTelefon> <teslimsekli>KR</teslimsekli> <tasiyicifirma>MNG</tasiyicifirma> <teslimkod1/> <teslimkod4/> <teslimil>İstanbul</teslimil> <teslimilce>Tuzla</teslimilce> <faturaalici/> <faturaAdresi>İncir Elektrizm. A.Ş. rnYahya Kemal Mah. Şair Plaza Kağıthane ul</faturaAdresi> <faturaTelefon>05014</faturaTelefon> <faturavergino>478034</faturavergino> <faturavergidairesi>Zincirlikuyu</faturavergidairesi> <faturail>İstanbul</faturail> <faturailce>Kağıthane</faturailce> <kargokodu>YT986031</kargokodu> <ODEME_SEKLI>Havale/ EFT</ODEME_SEKLI> <kargo_odemesi>Alıcı Öder</kargo_odemesi> // KARGO ÖDEME BİLGİSİ <SATIRLAR> <SATIR> <KOD>U66YT0554P</KOD> <VARKOD>VARYAN-KODU-GELECEK</VARKOD> <MIKTAR>1</MIKTAR> <BIRIM>Ad.</BIRIM> <FIYAT>11.16</FIYAT> <KDV>18</KDV> </SATIR> <SATIR> <KOD>N5YT0352</KOD> <VARKOD>VARYAN-KODU-GELECEK</VARKOD> <MIKTAR>2</MIKTAR> <BIRIM>Ad.</BIRIM> <FIYAT>16.74</FIYAT> <KDV>18</KDV> </SATIR> <SATIR> <KOD>I19YT0051</KOD> <VARKOD>VARYAN-KODU-GELECEK</VARKOD> <MIKTAR>1</MIKTAR> <BIRIM>Ad.</BIRIM> <FIYAT>2.33</FIYAT> <KDV>18</KDV> </SATIR> <SATIR> <KOD>X73YT3148</KOD> <VARKOD>VARYAN-KODU-GELECEK</VARKOD> <MIKTAR>3</MIKTAR> <BIRIM>Ad.</BIRIM> <FIYAT>5.12</FIYAT> <KDV>8</KDV> </SATIR> <SATIR> <KOD>MNG</KOD> <VARKOD>VARYAN-KODU-GELECEK</VARKOD> <MIKTAR>1</MIKTAR> <BIRIM>Ad.</BIRIM> <FIYAT>0.00</FIYAT> <KDV>18</KDV> </SATIR> </SATIRLAR> </SIPARIS> </SIPARISLER> my views for django: try: response = requests.get(URL) if response.status_code != requests.codes.ok: print("XML'i Çekemedik") veri = xmltodict.parse(response.content) print("veri dict edildi") siparisler = veri['SIPARISLER']['SIPARIS'] for siparis in siparisler: siparis_no = siparis['SIPARIS_NO'] print("!", siparis_no, " kaydı kontrol ediliyor..") qs = Siparisler.objects.filter(siparis_no=siparis_no) exists = qs.exists() if not exists: print("!", siparis_no, " kayıt ediliyor..") try: pazar_yeri_kargo_kodu = siparis['PAZARYERI_KARGOKODU'] siparis_tarih = … -
Django dictionary sort by value
Now, I am making a web that tells how many words are in the input I want to post top 15 most-used words as well def count(request): entered_text = request.GET['textarea'] word_list = entered_text.split() word_dictionary = {} for word in word_list: if word in word_dictionary: word_dictionary[word] += 1 else: word_dictionary[word] = 1 return render(request,'count.html', {'alltext':entered_text, 'total':len(word_list), 'dictionary':word_dictionary.items()}) These are codes that I made right now. I want to sort word_dictionary by value. I tried to use sorted function which I used in python but it doesn't work Is there any ways to sort word_dictionary? -
Confusion in id parameter in django
I was making an E Commerce website and added various products in it. Now for making a cart i made a add to cart button. And in HTML i assigned an id to this button. The id was pr{{product.id}}. I have not made buttons individually for every item. There is a for loop running which creates buttons. Now My doubt is that i have not assigned any field id in the models class. But still this code is running and when i printed the id's on the console i realised that it prints like pr32, pr33, pr34 ie in a sequential manner. So is there any product.id field predefined in django?? -
Serialize ManyToManyField with foreign key of nested
I need to serialize attributes of an item related from many to many, but grouped by each type of attribute. Models from django.db import models class AtributoTipo(models.Model): nombre = models.CharField(max_length=40) slug = models.SlugField(max_length=40, unique=True) class Atributo(models.Model): tipo = models.ForeignKey(AtributoTipo, on_delete=models.CASCADE) nombre = models.CharField(max_length=40) slug = models.SlugField(max_length=40) class Articulo(models.Model): codigo = models.CharField(max_length=18, unique=True, db_index=True) nombre = models.CharField(max_length=255) atributos = models.ManyToManyField(Atributo, related_name="articulos") Normal DRF serializers: from rest_framework import serializers class AtributoTipoSerializer(serializers.ModelSerializer): class Meta: model = AtributoTipo fields = ["__all__"] class AtributoSerializer(serializers.ModelSerializer): tipo_slug = serializers.ReadOnlyField(source="tipo.slug") tipo_nombre = serializers.ReadOnlyField(source="tipo.nombre") class Meta: model = Atributo fields = ["__all__"] class ArticuloSerializer(serializers.ModelSerializer): atributos = AtributoSerializer(many=True, read_only=True) # the dude class Meta: model = Articulo fields = ["__all__"] This is the result with serializers without any weird method: { "id": 44906, "codigo": "DE0058751", "atributos": [ { "id": 15107, "tipo": 76, "tipo_slug": "talla", "tipo_nombre": "Talla", "nombre": "39", "slug": "39" }, { "id": 43454, "tipo": 76, "tipo_slug": "talla", "tipo_nombre": "Talla", "nombre": "40", "slug": "40" }, { "id": 23234, "tipo": 15, "tipo_slug": "color", "tipo_nombre": "Color", "nombre": "Rojo", "slug": "rojo" }, { "id": 12408, "tipo": 15, "tipo_slug": "color", "tipo_nombre": "Color", "nombre": "Verde", "slug": "verde" } ] } Desired result: { "id": 44906, "codigo": "DE0058751", "atributos": [ "tipo": [ { "id": 76, "slug": … -
Print Barcode in PDF with Django
I am using render_to_string in django for parse an HTML and export to PDF. html = render_to_string("etiquetaTNT.html", { 'context': context, 'barcode': b, 'barcodeimg': barcodeimg, }) font_config = FontConfiguration() HTML(string=html).write_pdf(response, font_config=font_config) return response I am trying to insert a barcode in PDF. I generate this barcode in a PNG. br = barcode.get('code128', b, writer=ImageWriter()) filename = br.save(b) barcodeimg = filename But the PDF in template, not show the image. <img class="logo" src="{{barcodeimg}}" alt="Barcode" /> I do not know the way to save the filename in the template that I want, and I do not know to show in the PDF, because any image is showed. For example, the logo, it is showed in HTML template but not in the PDF. <img class="logo" src="{{logo}}" alt="TNT Logo" /> -
self._handle = _dlopen(self._name, mode) OSError: [WinError 126] The specified module could not be found
I am using geodjango to implement Google Map API in my web application. I configured the database in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geodjango_project', 'USER': 'postgres', 'HOST': 'localhost', 'PASSWORD': 'postgres', 'PORT': '5432' }, } I got this error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal204", "gdal203", "gdal202", "gdal201", "gdal20"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. then according to the instruction of the error, I added `GDAL_LIBRARY_PATH = r'C:\OSGeo4W64\bin\gdal202'` and this error was thrown: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\programdata\anaconda3\Lib\threading.py", line 917, in _bootstrap_inner self.run() File "c:\programdata\anaconda3\Lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load …