Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Add Record invalid literal for int() with base 10
I have the model models.py class StopRequestLog(models.Model): STOP_REQUEST_STATUSES = ( ('New', 'New'), ('Pending', 'Pending'), ) rafiki_profile_id = models.ForeignKey(RafikiProfileModel, on_delete=models.CASCADE, null=True) vehicle_profile_id = models.ForeignKey(VehicleProfile, on_delete=models.CASCADE, null=True) driver_profile_id = models.ForeignKey(DriversProfile, on_delete=models.CASCADE, null=True) tega_id = models.ForeignKey(Tega, on_delete=models.CASCADE, null=True) created_date = models.DateField(auto_now=False, null=True) created_time = models.TimeField(auto_now=False, null=True) completed_date = models.DateField(auto_now=False, null=True) completed_time = models.TimeField(auto_now=False, null=True) status = models.CharField(choices=STOP_REQUEST_STATUSES, max_length=30) Admin.py class StopRequestLogAdmin(admin.ModelAdmin): fields = ['rafiki_profile_id', 'vehicle_profile_id', 'driver_profile_id','tega_id', 'created_date', 'created_time', 'completed_date', 'completed_time' ,'status'] list_display = ['rafiki_profile_id', 'vehicle_profile_id', 'driver_profile_id','tega_id', 'created_date' , 'created_time', 'completed_date', 'completed_time','status'] readonly_fields = ['created_date', 'created_time', 'completed_date', 'completed_time'] Upon opening the Model and trying to add a record I get the error invalid literal for int() with base 10: b'07 08:49:15.819365' This b'07 08:49:15.819365' always being my current server time Please assist. -
ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from -r /tmp/build_97769b8b/requirements.txt (line 2))
while deploying my Django app Heroku it shows this error although all the requirements are already satisfied when I install it manually, my os is ubuntu 20, using pip3 for installation, Django 3.0.1 git push heroku master Enumerating objects: 88, done. Counting objects: 100% (88/88), done. Delta compression using up to 4 threads Compressing objects: 100% (80/80), done. Writing objects: 100% (88/88), 926.04 KiB | 10.18 MiB/s, done. Total 88 (delta 25), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.8.6 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.8.2 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting appdirs==1.4.4 remote: Downloading appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB) remote: ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from -r /tmp/build_97769b8b/requirements.txt (line 2)) (from versions: none) remote: ERROR: No matching distribution found for apturl==0.5.2 (from -r /tmp/build_97769b8b/requirements.txt (line 2)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to mygamlaapp. remote: To https://git.heroku.com/mygamlaapp.git ! … -
Unexpected datetime behavior
I have a Django project where I used the strftime function like this in views.py: .strftime("%b %-d %Y, %-I:%M %p") However, for some reason this returns a ValueError, even though according to the documentation this is a valid format string. Once I removed all the dashes, it worked normally. Why doesn't this work? Do I need to import a module or something? Thanks. -
What should I use to make a takeaway ordering site? [closed]
I'm creating a website for a takeaway restaurant but I'm not really too sure as to what backend service I should use. I am going to be using python and I already know the flask framework pretty well. I don't know if for something like this I should just switch to Django as there is going to be user accounts, credit card payments, etc. Kind of just what you would expect of a takeaway website. Should I just bite the bullet and do this in Django or should I stick with Flask for a project like this? -
(Django) Call field names in template from an annotation of values?
I'm trying to build a school management system, and I want to display the total points (and eventually a letter grade) by each course a student is in. This is my model for student's assignments: class StudentAssignment(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE) points_earned = models.IntegerField(blank=True, null=True) feedback = models.TextField(blank=True, null=True) def get_absolute_url(self): return reverse('assignments_all_students', args=[str(self.assignment.pk)]) In my view when a student clicks on their current courses: @login_required def my_courses(request): user = request.user student = Student.objects.filter(user=user).first() all_assignments = StudentAssignment.objects.filter(student=student) #This groups the assignments by each course, then divides it by total points to get a percentage all_scores = all_assignments.values('assignment__session_link').annotate(score=(Cast(Sum('points_earned'), FloatField()) / Cast(Sum('assignment__total_points'), FloatField()) * 100)).exclude(points_earned=None) if student is None: return render(request, 'users/not_student.html') active_classes = student.enrolled_courses.all() if len(active_classes) == 0: return render(request, 'users/no_courses.html') context = {'classes': active_classes, 'scores': all_scores} return render(request, 'users/my_courses.html', context) The problem is now my 'scores' context has no field names anymore, so I can't reference anything in the template to show things like course title, description, etc. Is there a way to get these field names, or is it better to add a field to my StudentAssignment that can do the percentage calculation after a teacher grades it? -
Delete notification for django-notification-hq
I am using the package django-notifications-hq for my notification system, however, I cannot delete notification with my views. Now in the notifications model in the package we have: recipient = models.ForeignKey( settings.AUTH_USER_MODEL, blank=False, related_name='notifications', on_delete=models.CASCADE ) actor_content_type = models.ForeignKey(ContentType, related_name='notify_actor', on_delete=models.CASCADE) actor_object_id = models.CharField(max_length=255) actor = GenericForeignKey('actor_content_type', 'actor_object_id') target_content_type = models.ForeignKey( ContentType, related_name='notify_target', blank=True, null=True, on_delete=models.CASCADE ) target_object_id = models.CharField(max_length=255, blank=True, null=True) target = GenericForeignKey('target_content_type', 'target_object_id') I am trying to access each users notification with request.user.notifications However, everytime I get the error: <class 'notifications.models.Notification.DoesNotExist'> I try removing the notification by: from django.contrib.admin.options import get_content_type_for_model request.user.notifications.get(actor_content_type=get_content_type_for_model(user),actor_object_id=str(user.id),\ recipient=post.author, verb=message, target_content_type=get_content_type_for_model(post), target_object_id=str(post.id)).delete() in the above example request.user is post.author How can I remove my notifications within my views? -
Posting remote CSV file data to django local server issue
so I have a Raspberry Pi collecting data in a CSV file that is stored locally on the Pi. The Raspberry Pi is connected to a university network so to access the Pi remotely, I just have to be connected to the university network and have a remote project interpreter set up in my PyCharm IDE. I've written a script that accesses the specific CSV file on the local Raspberry Pi and then posts each line of data to a local Django server. But I keep getting an error when I run it. I have tested the local Django server and script with a local CSV file on my own computer, and it worked correctly. The error I keep getting is: requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /datavaluetable/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x75194050>: Failed to establish a new connection: [Errno 111] Connection refused')) My first thoughts to fix the issue were: Make sure my local server was actually running (it is) Disable my Windows firewall Place the actual CSV file reading script onto the Raspberry Pi itself, then running it Double check my project interpreter (this is set up correctly since I can access other Python files … -
Block evaluation of template tags but not variables
I am using Django's template engine to evaluate user-supplied template strings. I would like to allow the users to use the variable mapping functionality, but not the tags or filters. For example: from django.template import Context, Template user_template_string = "V1: {{ var1 }}. V2: {{ var2|truncatechars:5 }}. {% if var3 %} yes {% else %} no {% endif %}" template = Template(user_template_string) context = {'var1': 'One', 'var2': '123456789', 'var3': True} output = template.render(context=Context(context)) # Desired output: # "V1: One. V2: 123456789. {% if var3 %} yes {% else %} no {% endif %}" Is there a way to configure the template engine to render variables but ignore tags and filters? Or is my best bet to sanitize the user input and try to strip out all tags and filters that they may include? -
Putting a django application on production using IIS Server is raising an error
I am trying to put on production a Django web app using IIS Server but I am getting this error: Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\programdata\anaconda3\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\programdata\anaconda3\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\programdata\anaconda3\lib\site-packages\wfastcgi.py", line 616, in get_wsgi_handler raise ValueError('"%s" could not be imported%s' % (handler_name, last_tb)) ValueError: "SGC.wsgi.application" could not be imported: Traceback (most recent call last): File "c:\programdata\anaconda3\lib\site-packages\wfastcgi.py", line 600, in get_wsgi_handler handler = __import__(module_name, fromlist=[name_list[0][0]]) File ".\SGC\wsgi.py", line 16, in <module> application = get_wsgi_application() File "c:\programdata\anaconda3\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "c:\programdata\anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "c:\programdata\anaconda3\lib\site-packages\django\apps\registry.py", line 92, in populate app_config = AppConfig.create(entry) File "c:\programdata\anaconda3\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "c:\programdata\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'ckeditor' StdOut: StdErr: In my application everything about creditor is installed. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hr.apps.HrConfig', 'account', 'courriers', 'rolepermissions', 'crispy_forms', 'admin_tools', 'cart.apps.CartConfig', 'enregistrement', 'ckeditor', 'debug_toolbar', ] Here is my web.config file: <system.webServer> <handlers> <add name="SCG SERVER" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\programdata\anaconda3\python.exe|c:\programdata\anaconda3\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="PYTHONPATH" value="F:\SGC" /> <add key="WSGI_HANDLER" value="SGC.wsgi.application" /> … -
How to add a variable through 'annotate' that is responsible for the presence of the current user in the list of values of one of the model fields
I have these models: class ProfilePost(models.Model): author = models.ForeignKey(Profile, on_delete=models.CASCADE) post_text = models.TextField(max_length=10000) publication_date = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField(Profile, related_name='like') class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) profile_picture = models.ImageField(default='/pictures/default.png', upload_to='pictures/', blank=True) city = models.CharField(max_length=63, blank=True) phone = models.CharField(max_length=15, blank=True) def get(self, request, user_id, *args, **kwargs): user = get_object_or_404(User, id=user_id) if request.GET and request.GET['request_type'] == 'get_extra_posts': posts2 = ProfilePost.objects.filter(author=user.profile).order_by('-publication_date') posts_with_users_likes = list(request.user.profile.like.all().values_list('id', flat=True)) print(posts_with_users_likes) # [21, 11, 10, 8, 6, 1] posts2 = posts2.annotate( like_count=Count('like', distinct=True), comment_count=Count('postcomment', distinct=True), is_liked_by_user=Value(len(Q(id__in=posts_with_users_likes)), output_field=BooleanField()) ) posts2 = posts2.values('id', 'post_text', 'publication_date', 'is_liked_by_user', 'like_count', 'comment_count') print(posts2) return JsonResponse(data={'posts': posts2}) In my views.py I want to add some extra fields to the ProfilePost Queryset, but I am having problems with the is_liked_by_user field, which should be True if the current user has liked this post and False otherwise. The line print(posts2) outputs <QuerySet [{'id': 12, 'post_text': '6', 'publication_date': datetime.datetime(2020, 10, 1, 18, 2, 29, 635769, tzinfo=<UTC>), 'like_count': 0, 'comment_count': 0, 'is_liked_by_user': True}, {'id': 11, 'post_text': '5', 'publication_date': datetime.datetime(2020, 10, 1, 18, 2, 21, 401305, tzinfo=<UTC>), 'like_count': 1, 'comment_count': 0, 'is_liked_by_user': True}, {'id': 10, 'post_text': '4', 'publication_date': datetime.datetime(2020, 10, 1, 18, 0, 49, 402443, tzinfo=<UTC>), 'like_count': 1, 'comment_count': 1, 'is_liked_by_user': True}, {'id': 9, 'post_text': '3', 'publication_date': datetime.datetime(2020, 10, … -
Facebook Share Button from Django App add <meta/>
I'm working on Django 2.0.13 and I'm trying to add button to share on facebook on my news.html template but when I click on share I don't see the image or the content of the shared new. Thanks for your help. {% for new in news %} <div class="row" id="{{ new.id }}" style="border-bottom:2px solid #000000; padding-top:20px; padding- bottom:20px"> {% if new.photo %} <div class="col-md-3"> <img src="{{ new.photo.url }}" alt="photo de {{new.photo.title}}"/> </div> <div class="col-md-9"> {% else %} <div class="col-md-12"> {% endif %} <div id="texte_middle" class="page"> <h3>{{ new.title }}</h3><br> <h4>{{ new.date_created}}</h4> <p>{{ new.content|safe }}</p> {% if new.share_button_active %} {% block extra_head_tags %} <meta property="og:title" content= "{% if new %} {{new.title}} {% else %} News {% endif %}" /> <meta property="og:image" content="{{new.photo.url}}" /> <meta property="og:description" content={{new.content|safe}} /> <!-- Sharingbutton Facebook --> <a class="resp-sharing-button__link" href="https://facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}%23{{ new.id }}" target="_blank" rel="noopener" aria-label="" > <div class="resp-sharing-button resp-sharing-button--facebook resp-sharing-button--small"><div aria- hidden="true" class="resp-sharing-button__icon resp-sharing-button__icon--solidcircle"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 0C5.38 0 0 5.38 0 12s5.38 12 12 12 12-5.38 12-12S18.62 0 12 0zm3.6 11.5h-2.1v7h-3v-7h-2v-2h2V8.34c0-1.1.35-2.82 2.65- 2.82h2.35v2.3h-1.4c-.25 0-.6.13-.6.66V9.5h2.34l-.24 2z"/></svg> </div> </div> </a> {% endblock %} {% endif %} -
How to filter the amount of options which the user can choose depending on the previous selected option (DJANGO)
I have been trying for a while to implement a filter system in which it changes the options that the user can select depending on the previous option chosen in my DJANGO application. The process is like that :[The user will select a school][then depending the school that the user has chosen just the courses this school has will be displayed] [then after selecting the course the only options the user will have are the ones that are related to School -> Course - > Classes - > Semester then all the books with the exactly matching metadata will be displayed. Does someone can guide me or give some ideas on how I can implement that ? I have tried many to many and one to many relationships already but I was not successful :/ Also for real time changes will I have to implement AJAX with the application for that ? Thank you for your time :) Here is a image to show how the application will look like: https://i.stack.imgur.com/xympT.png -
DoesNotExist at /blog/postComment Post matching query does not exist
I am trying to print the comments below the blog but after clicking the submit button the above error shows up. I just want a success message to be displayed on the top of the web page, for which I have written the line: messages.success(request, 'your comment has been added'), but the error shows up! models.py: from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now # Create your models here. class Post(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=50) content = models.TextField() author = models.CharField(max_length=50) slug = models.SlugField(max_length=200) timeStamp = models.DateTimeField(blank=True) def __str__(self): return self.title + " by " + self.author class BlogComment(models.Model): sno = models.AutoField(primary_key=True) comment = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) timestamp = models.DateTimeField(default=now) urls.py: from django.urls import path, include from blog import views urlpatterns = [ path('postComment', views.postComment, name='postComment'), path('', views.blogHome, name='home'), path('<str:slug>', views.blogPost, name='blogpost'), ] view.py: from django.shortcuts import render, HttpResponse, redirect from blog.models import Post, BlogComment def blogHome(request): allpost = Post.objects.all() context = {'allposts': allpost} return render(request, 'blog/blogHome.html', context) def blogPost(request, slug): post = Post.objects.filter(slug=slug).first() comments = BlogComment.objects.filter(post=post) context = {'post': post, 'comments': comments} return render(request, 'blog/blogPost.html', context) def postComment(request): if request.method == 'POST': … -
Heroku not updating static files for Django webapp
I noticed that recently my static files on my Django web app are not being updated on my website despite being successfully pushed to Heroku master, and working fine locally. Now I have tried several steps: I first got my git status and it says Everything up to date. My DNS Host is CloudFare so I have done Purge Cache and still nothing. I have also triied heroku repo:purge_cache -a appname to delete my cache and then ran an empty commit and still nothing. I have deleted my browser cache several times and still, my static files are not being updated despite me running python manage.py collectstatic and heroku run python manage.py collectstatc and committed, yet nothing. Now is there anything that I have missed? I do not know any other method to update my static files. -
xamarin froms parse JSON from django rest framework
I can successfully register with my xamarin forms app in django website and if username or email already exist i receive http response from django rest framework in this format : { "username": [ "account with this username already exists." ], "email": [ "account with this email already exists." ] } i want to show these errors in display alert without username and email. only text of error ( for example: account with this username already exists or account with this email already exists) i've tried to parse it in a lot of ways but none of them worked. how can i achieve it? code in my app: HttpClient client = new HttpClient(); var values = new Dictionary<string, string> { { "username", EntryUsername.Text }, { "email", EntryEmail.Text }, { "password", EntryPassword1.Text }, { "password2", EntryPassword2.Text } }; var content = new FormUrlEncodedContent(values); var response = await client.PostAsync("http://192.168.0.101:8000/api/account/register", content); var responseString = await response.Content.ReadAsStringAsync(); -
How to call user variables in Django ModelAdmin
I am new to Django and having trouble understanding how to call proper variables in a ModelAdmin. If I am on /admin/mt_app/my_model/ that I have information like the user's name OR I'm on /admin/auth/user/2/change/ that has all the user's information, how do I call those variables in the ModelAdmin View? I got it working selectively by plugging in my own user, but I can't figure out how to call the relevant user or model from the view. All I can find is how to call the current user, but again, I need the user of the that the page is regarding, not the active user. Ex: /admin/algorx/pt_data/41/change/ or /admin/auth/user/2/change/ What I have now is: Admin.py class pt_dataAdmin(admin.ModelAdmin): fieldsets = ( . . . ) # This gets passed into change_view as extra context def get_dynamic_info(self): user = User.objects.get(email='MYSUPERUSEREMAIL') return user . . . def change_view(self, request, object_id, form_url='', extra_context=None): . . . So what works is passing in my super user's email to select that user: user = User.objects.get(email='MYSUPERUSEREMAIL') return user But what I want to do is select the user of the current page being viewed. If I'm on the following URL how do I select that user's variable? … -
Django TestCase to validate a ModelForm over multiple Models
I have flexible data models representing network switches and their individual ports that look similar to below (with apologies for the name of the first; unfortunate but I could think of no better): class Model(models.Model): name = models.CharField(max_length=20, unique=True) port_count = models.IntegerField() ... class Switch(models.Model): model = models.ForeignKey(Model, on_delete=models.CASCADE) name = models.CharField(max_length=14, unique=True) ... class Port(models.Model): switch = models.ForeignKey(Switch, on_delete=models.CASCADE) number = models.IntegerField() ... Data entry is validated to ensure Port.number is within the range of 1 to Model.port_count. This was a trivial TestCase to author. Another important validation is for my ModelAdminForm.clean() to ensure that reducing Model.port_count would not make any existing Port records violate the new range. (Those ports would likely need to be deleted first.) Authoring this clean() method was also trivial, but authoring a TestCase for this validation has landed me in new territory without a map or guide. Since such a test requires a bit of initial DB population, I created a helper: def add_one(cls, **kwargs): _log.info(f'adding one {cls.__name__}') return cls.objects.create(**kwargs) I started by developing the TestCase to mimic an edit of Model.port_count that would not have any issues, to prove my transactional parts correct. Later, I would extend the code so that there would … -
How to select an instance of a model from a queryset django?
I am creating a project for hosting cricket tournaments. I have created 3 apps in it: home, tournament and team. After adding a tournament, when entering the tournament's detail view, I can add a team to the tournament. My Team model has a ForeignKey to my Tournament model, and my Tournament model has a ForeignKey to my User model(built-in django user model). When creating a team, I want to save the team for a particular tournament. I don't understand how to access the exact tournament and save the team for that tournament only. My tournament detail html: {% extends 'menu.html' %} {% block content %} <div class="row"> <div class="col-8"> <table class="table table-bordered table-hover"> <tr> <th scope="col">Match between</th> <th scope="col">Winner</th> </tr> {% for match in match_list %} <tr> <td> {{ match.team1.name }} vs {{ match.team2.name }} </td> <td> {% if match.winner %} {{ match.winner.name }} {% else %} TBD {% endif %} </td> </tr> {% endfor %} </table> </div> <div class="col-4"> {% if teamscount < tournament.no_of_teams %} <button class="btn btn-primary" onclick="window.location.href='{% url 'teams:addteam' %}'">Add Team</button> {% endif %} </div> </div> {% endblock content %} My urls.py file in tournament app: from django.urls import path, include from . import views app_name='tournaments' urlpatterns … -
serializer field with "allow_null" automatically sets value to null
I have the following serializer class NiceSerializer(serializers.Serializer): nice_field = serializers.CharField(required=False, allow_null=True) another_field = serializers.IntegerField(required=False) I need the nice_field to be nullable, that's why I put allow_null=True, however, sometimes I make a patch request that should only update the value of another_field, so the request does not contain the nice_field value. The problem is that the after validating the request data the NiceSerializer automatically set the value to None, which is a very inconvenient behaviour. How can I write a serializer where I can eventually ignore a field in the patch request? Thanks a lot -
How to pass values of a dropdown list from html to python using django
I am sure this is a simple syntax issue I am not able to resolve. I just started working in django to try to move away from tkinter for my python hobby project. List below are my views, template, and url files. All I want for my front end GUI is to have a user select a file path, a Area, and a type of output. I plan on pass off this values to python to do some logic with. from django.shortcuts import * from django.http import * # Create your views here. def home(request): return render(request, 'home.html') def page_objects(request): Area = request.GET["Area"] Output = request.GET["Output"] print(Area) print(Output) return render(request, 'home.html') <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <h2>Please Select Your Document, and the Area</h2> <p>Move the mouse over the button to open the dropdown menu.</p> <p>Then hit submit!</p> <p> <label for="myfile">Select a file:</label> <input type="file" id="myfile" name="myfile"> </p> <form action="/views" method="post"> <select name="Area"> <option selected="selected" disabled>Objects on page:</option> <option value="P10">P10</option> <option value="P20">P20</option> <option value="P30">P30</option> <option value="P40">P40</option> <option value="P50">P50</option> </select> <select name="Output"> <option selected="selected" disabled>Objects on page:</option> <option value="List">List</option> <option value="Address">Address</option> </select> <input type="submit" value="Select"> </form> </body> </html> from django.urls import path from . import views urlpatterns … -
django-allauth-sendgrid password reset email not received
I have integrated sendgrid in my app as follows: SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = SENDGRID_API_KEY EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = "from@example.com" I run a test from manage.py shell as the below and I received the test email. from django.core.mail import send_mail send_mail('Subject here', 'Here is the message.', 'from@example.com', ['to@example.com']) On my website, after clicking forget password and filling in a registered user email, the page directs to a page that says email sent. But I did not received any email. There is no debug info and I cannot figure out where it went wrong. I am on pythonanywhere is that makes a difference. -
django ajax login form login without page refresh
i followed a tutorial online that shows how to submit a form with ajax and i ended up with just submitting the form and a meesage gets rendered in the console that says it worked , but i want the prosses to work and the user signin or if there are errors , those errors appears without the need of page refresh i mean with the help of ajax. in my forms.py class SigninForm(forms.ModelForm): class Meta: model = User fields = ('email', 'password') widgets = { 'email': forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control','id':'signin_email'}), 'password': forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control','id':'signin_password'}), } def clean(self): if self.is_valid(): email = self.cleaned_data['email'] password = self.cleaned_data['password'] the email input has an id of "signin_form" and the password has an id of "signin_password" in my views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout as django_logout from django.http import JsonResponse from django.contrib import messages from .models import * from .forms import * def home(request): user = request.user signin_form = SigninForm() if request.is_ajax(): signin_form = SigninForm(request.POST) if signin_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) data = { 'message':'it's working successfully' } return JsonResponse(data) context = {'signin_form': signin_form,'signup_form': signup_form} return render(request, 'main/home.html', context) in my … -
Django models.py (API result) - retrieve current post to add api result
I'm new to Django I got an issue. I don't know how to retrieve the current post inside of models.py. I've tried different way for that. 'QuerySet' object has no attribute 'aliments' or no error and no add to Post from ListAliments get_object_or_404(Post, id=kwargs['id']) here is my models.py class ListAliments(models.Model): name = models.CharField(max_length=40, unique=True) slug = models.SlugField(editable=False) status = models.IntegerField(choices=STATUS, default=1) def save(self, *args,**kwargs): if not self.slug: self.slug = unique_slugify(self, slugify(self.name)) super(ListAliments, self).save(*args, **kwargs) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=190) url_image = models.URLField(max_length=200, default=None) aliments = models.ManyToManyField('ListAliments',blank=True, related_name='listaliments_post') ... def save(self, *args, **kwargs): if not self.slug: self.slug = unique_slugify(self, slugify(self.title)) super(Post, self).save(*args, **kwargs) -> First save for Post which has not no ID ... if self.url_image: request = ... response = ... if response: names = [] for concept in response.outputs[0].data.concepts: current_aliments = ListAliments.objects.filter(name=concept.name) current_post = Post.objects.filter(url_image=self.url_image) #get_object_or_404(Post, id=kwargs['id']) if current_aliments.count()<1: create_aliments = self.aliments.create(name=concept.name) current_post.aliments.add(create_aliments) else: existed_aliments = ListAliments.objects.get(name=concept.name) current_post.aliments.add(existed_aliments) super().save(*args, **kwargs) -
How to convert bytes to a string of the same length in Python (1 character for each byte)?
I need a random string that I can write down to use for salt in a hash function. I can generate some random bytes and see them as hex: import os, binascii print(binascii.b2a_hex(os.urandom(32))) b'76449cd6134d64353122102fcb512d1eae1bd8437202b6e06e91a422ce9e386b' # 64 chars Great, but how do I convert these bytes directly to a string i.e. not necessarily printable, but exactly 32 characters? The hash function requires a string, not a "bytes" type with a maximum length of 32. I'm not sure how to do the encoding in Python, but I guess I need something similar to the way an old 8-bit computer or a C program would turn a byte into a character (ASCII or other). This is for the salt input of Django's make_password function. -
New users are not able to create an account and Login and Register urls are redirection to same page Django
I am trying to build a simple authentication system using Django. Both Login and Register urls on 'accounts' are redirecting to the same Login page. After I login as an admin, I'm redirected to register page. In the register page, I'm not able to register new accounts. Please tell me what I'm missing. urls.py-login from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')) ] urls.py-accounts from django.urls import path from . import views from django.contrib.auth.views import LoginView, LogoutView urlpatterns = [ path('', views.indexView, name = "home"), path('dashboard/', views.dashboardView, name = "dashboard"), path('login/', LoginView.as_view(), name = "login_url"), path('register/',views.registerView, name = "register_url"), path('logout/', LogoutView.as_view(next_page='dashboard'), name = "logout"), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.decorators import login_required # Create your views here. def indexView(request): return render(request, 'index.html') def dashboardView(request): return render(request, 'dashboard.html') @login_required def registerView(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login_url') else: form = UserCreationForm() return render(request, 'registration/register.html', {'form':form}) index.html <!DOCTYPE html> <html> <head> <title>Petrol Pump Management System</title> </head> <body> {% block content %} <h1>User Authentication</h1> {% if user.is_authenticated %} <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login_url' %}">Login</a> <a href="{% …