Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django views.py: Add to favorites page
I am trying to edit an html page so a logged in user can favorite a video.id Here is the .html file <td> <form method='POST' action="{% url 'foobar:favourite_post' video.id %}"> {% csrf_token %} <input type='hidden' name='video' value={{ video.id }}> <button type='submit'>Bookmark</button> </form> </td> Here is the urls.py file path('<int:fav_id>/favourite_post', views.favourite_post, name='favourite_post'), Here is the view.py file def favourite_post(request, fav_id): video = get_object_or_404(Video, id=fav_id) if request.method == 'POST': #Then add this video to users' favourite video. return render(request, 'foobar/%s' % fav_id) How to edit the views.py file so it is registered in the database that the user has favorited this video ? Here is the models.py file class Video(models.Model): name = models.CharField(max_length=255), videofile = models.FileField(upload_to="static/videos/"), favourite = models.ManyToManyField(ProjectUser, related_name="fav_videos", blank=True) -
Django - how to fix - request.POST.get returns None?
I'm learning django and trying to get the user's vote from a detailview. The user chooses from radio buttons and clicks on a submit button. The detailview's template's form's action is set to a formview url. Inside the urls I have require_POST on the formview. Inside the template and a for loop: <input type="radio" name="choice" value="{{one.name}}"> <label for="{{one.name}}">{{one.name}}</label><br> Inside a form view: def form_valid(self, form): request = HttpRequest() vote = request.POST.get('choice') return HttpResponse(vote) When I submit the form I can see the choice param in firefox network under post method but the view returns None. What am I doing wrong? -
pinax notifications urls - NoReverseMatch
I am attempting to implement pinax-notifications. The actual implementation is fine and I have created my notifications. I installed the templates in /templates/pinax/notifications according to the instructions. However, when I go to http://127.0.0.1:8000/notifications/ it just falls back to the home page. urls.py urlpatterns = [ url(r'^accounts/', include('allauth.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', admin.site.urls), url(r'^users/', include('users.urls')), url(r"^notifications/", include("pinax.notifications.urls", namespace="pinax_notifications")), url(r'', IndexView.as_view(), name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) related installed apps ... "pinax.notifications", "bootstrapform", "pinax.templates", Template processing TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'debug': True, 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', ], }, }, ] I do not get any other errors. Any ideas on the next step or am I overlooking an obvious error? -
Model not user specific
I have a model called Post. The data in Post is displayed to every user while I want this to be user specific. I'm new to Django. This app is created following the Django for Girls tutorial. I later added support for user registration. models.py: from django.conf import settings from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Example from views.py: from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Post from .forms import PostForm from django.contrib.auth.forms import UserCreationForm from django.shortcuts import redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate @login_required def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) Example from the template (post_list.html): {% for post in posts %} <div class="post"> <div class="date"> <p>published: {{ post.published_date }}</p> </div> <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1> <p>{{ post.text|linebreaksbr }}</p> </div> {% endfor %} -
Prevent deleting ManyToMany item
I have models.ManyToManyField, how can I prevent deleting a specific element of ManyToMany in Django admin panel? For example, available options are: dog cat spider "Dog" should be impossible to delete. -
Django - Check if form submit button was clicked?
How can I specifically check if the submit button of my form was clicked? The if form.is_valid() validation does that check but also returns True without clicking the button (When the clean() method was executed). How can I set a variable to True when the submit button was clicked. I try to confirm a upload and when the user clicks the submit button it should execute a Database Query. Here is my views.py def file_upload(request): save = False if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) form2 = ConfirmationForm(request.POST, request.FILES) if cache.get('save'): print("True") save = True else: print("False") save = False print("request.POST: ", request.POST) print("request.FILES: ", request.FILES) print("save: ", save) print("form: ", form) print("form2: ", form2) if not request.FILES: print("empty") else: print("not empty") updated_obj = 0 created_obj = 0 duplicate_obj = 0 count = 0 # Prüfen ob CSV Datei valide ist (keine doppelten Datensätze) rs1 = list() rs2 = list() d_list1 = list() d_list2 = list() csv_file = get_data(request, save) csv_file.seek(0) file = csv_file.read().decode('utf-8').splitlines() reader = csv.reader(file) for row in reader: try: row_set1 = [row[0], row[1], row[2], row[3], row[4]] row_set2 = [row[5], row[6]] if row_set1 not in rs1: rs1.append(row_set1) else: d_list1.append(row_set1) if row_set2 not in rs2: rs2.append(row_set2) else: d_list2.append(row_set2) … -
Accidentally ran git clean -d -f and need to get back python3.7
Won't be running that again, but I've managed to salvage most everything except when I try to run git pull I get an error (because these files were removed) error: unable to create file /settings/__pycache__/__init__.cpython-37.pyc (Permission denied) error: unable to create file /settings/__pycache__/base.cpython-37.pyc (Permission denied) error: unable to create file /settings/__pycache__/dev.cpython-37.pyc (Permission denied) error: unable to create file /settings/__pycache__/local.cpython-37.pyc (Permission denied) error: unable to create file /settings/__pycache__/prod.cpython-37.pyc (Permission denied) Because running git clean -d -f . removed Removing lib/python3.6/ Removing lib/python3.7/site-packages/allauth/ Removing lib/python3.7/site-packages/autoslug/ Removing lib/python3.7/site-packages/captcha/ Removing lib/python3.7/site-packages/cities_light/ Removing lib/python3.7/site-packages/debug_toolbar/ Removing lib/python3.7/site-packages/defusedxml/ Removing lib/python3.7/site-packages/oauthlib/ Removing lib/python3.7/site-packages/openid/ Removing lib/python3.7/site-packages/progressbar/ Removing lib/python3.7/site-packages/python_utils/ Removing lib/python3.7/site-packages/ranged_response/ Removing lib/python3.7/site-packages/requests_oauthlib/ Removing lib/python3.7/site-packages/sqlparse/ Removing lib/python3.7/site-packages/unidecode/ Removing lib/python3.7/site-packages/whitenoise/__pycache__/ Removing lib/python3.7/site-packages/whitenoise/runserver_nostatic/__pycache__/ Removing lib/python3.7/site-packages/whitenoise/runserver_nostatic/management/__pycache__/ Removing lib/python3.7/site-packages/whitenoise/runserver_nostatic/management/commands/__pycache__/ Removing success.html Removing profile_pics/13958293_10209401380008125_7702518920572958301_o_2.JPG warning: failed to remove /settings/__pycache__/__init__.cpython-36.pyc warning: failed to remove /settings/__pycache__/base.cpython-36.pyc warning: failed to remove /settings/__pycache__/prod.cpython-36.pyc warning: failed to remove /settings/__pycache__/local.cpython-36.pyc Removing /static/ Removing /migrations/.0011_auto_20190217_1023.py.swp I don't want to do any more damage and am unsure of how to proceed. I'm running this Django Python project on Ubuntu 16.04, do I need to re-install python3.7? -
Trying to create nested view of django model classes using relations
I am trying to follow this documentation to create nested serializer and api view. https://www.django-rest-framework.org/api-guide/relations/#nested-relationships However, I am not able to understand what did I miss as my results are not expected. I have followed this example to my case and checked various other guides regarding same. Tried different views and different serializer formats. Code for model is this:- class Seats(models.Model): stack = models.IntegerField(null=False, default=0) player = models.ForeignKey(Participant, on_delete=models.CASCADE) state = models.IntegerField(choices=STATE) class Round(models.Model): player_num = models.IntegerField(null=False, default=1) code for Serializers is this:- class SeatsSerializer(serializers.ModelSerializer): class Meta: model = Seats fields = ('stack','state') class RoundSerializer(serializers.ModelSerializer): seats = SeatsSerializer(many = True, read_only=True) class Meta: model = Round fields = ('player_num','seats') I want output like this: { 'player_num': 3, 'seats': [ {'stack': 100, 'state': 'participating', 'name': 'p1', 'uuid': 'ftwdqkystzsqwjrzvludgi'}, {'stack': 100, 'state': 'participating', 'name': 'p2', 'uuid': 'bbiuvgalrglojvmgggydyt'}, ] } However, output I get is: { 'player_num': 3, } -
Django unable to delete/clear data on form
i have a edit_profile view at my django application that also checks if the pgp key the users saves to his profile is in RSA format, Anyways if i add a profile avatar for the very first time it works like a charm, if i want to clear or delete it, im always jumping onto the execpt block and the user avatar remains unchanged. Well i dont see a clear reason why at the point can maybe smb give me a hint here: views.py def edit_profile(request): if request.method == 'POST': form = UserForm(request.POST, request.FILES, instance=request.user) try: pubpgp = request.POST.get('pubpgp') if not pubpgp or PGPKey.from_blob(pubpgp.rstrip("\r\n"))[0].key_algorithm == PubKeyAlgorithm.RSAEncryptOrSign: form.save() messages.success(request, "Profile has been updated successfully.") return redirect(reverse('home')) else: messages.error(request, "Uuups, something went wrong, please try again.") return render(request, 'app_Accounts/edit_profile.html', {'form': form}) except: messages.error(request, "PGP-Key is wrong formated.") return render(request, 'app_Accounts/edit_profile.html', {'form': form}) else: form = UserForm(instance=request.user) args = {'form': form} return render(request, 'app_Accounts/edit_profile.html', args) -
How to fix code when changing from django 1.0 to 2.0
I need help in changing the url.py code in django 1.0 to django 2.0 I am a beginner in Django and I am following the book called "The Definitive Guide to Django". The book, however, uses Django 1.0 and I am using Django 2.0, the Django 2.0 syntax for the URLs is however different. and I have tried fixing it but it does not work. I am fine with suggestions on very good books that utilize Django 2.0 as well. I am still using this book "The Definitive Guide to Django" because I like how it presents things. All suggestions are welcome. This is my Url.py content from django.urls import include, path # Uncomment the next two lines to enable the admin: #from django.contrib import admin #admin.autodiscover() #from django.conf.urls.defaults import * from mysite.views import hello, current_datetime, hours_ahead urlpatterns = [ path('hello//', hello, name='hello'), #('^time/$', current_datetime), #(r'^time/plus/(\d{1,2})/$', hours_ahead) # Example: # (r'^mysite/', include('mysite.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/(.*)', admin.site.root), ] And my views.py file from django.http import HttpResponse import datetime from django.template import Context from django.template.loader … -
The image part error in django report and survey "TemplateDoesNotExist"
https://github.com/Pierre-Sassoulas/django-survey In the above-given repository, the image part does not work! How do I add images in the survey and can this also done with video? -
Django: How to create a signal for deleting a instance of pre_save signal?
I have the following pre_save signal in my models: @receiver(pre_save, sender=Purchase) def user_created_purchase_cgst(sender,instance,*args,**kwargs): c = Journal.objects.filter(user=instance.user, company=instance.company).count() + 1 if instance.cgst_alltotal != None and instance.cgst_alltotal != 0: Journal.objects.update_or_create( user=instance.user, company=instance.company, by=ledger1.objects.filter(user=instance.user,company=instance.company,name__icontains='CGST').first(), to=instance.party_ac, defaults={ 'counter' : c, 'date': instance.date, 'voucher_id' : instance.id, 'voucher_type' : "Journal", 'debit': instance.cgst_alltotal, 'credit': instance.cgst_alltotal} ) I want to create a signal that when the sender is deleted then the sender instance will also get deleted i.e when a Purchase object is deleted then the corresponding Journal object which is created by the pre_save signal will get deleted. Any idea anyone how to perform this? Thank you -
Default image not saving in DB
I have a requirement where if a user doesn't upload the image, the default image should be saved in DB for this I am using the default attribute in FileField but default image is not saving in DB. file = models.FileField(upload_to='photos/',default='NoImage.jpg') -
Relational database in django in a popup form
I have two tables in a django database which are as follows: Manufacturer and Transporter Both of these tables are filled by their respective forms. Now I have shown the data from Manufacturer onto a board like this and added a "BID NOW!" button too. When I click this button a popup opens which have all the prefilled entries with BID field and a submit and cancel button. Like this:- Now I want that when i enter a bid and press the submit button it should update Load_ID(on which we are bidding), Transporter_ID(bidder) and bid_amount and an automatic bid_id in a table. How do I do that ? and which fields should be made one-to-many/many-to-one ? Here is the code for manufacturer board: class ManufacturerBoardModel(models.Model): From = models.CharField(max_length=100,null=True) To = models.CharField(max_length=100,null=True) Type = models.CharField(max_length=100,null=True) Length = models.CharField(max_length=100,null=True) Weight = models.CharField(max_length=100,null=True) Numberoftrucks = models.IntegerField(null=True) MaterialType = models.CharField(null=True,max_length=100) Loadingtime = models.DateTimeField(null=True) def _str_(self): return self.Origin -
Some comments are missing when looped through mysql records via Django
For many hours now I have been working tirelessly to get this code working. I have requirements to display posts and comments results from database in json using sql queries via django Below is my expected json Format. [ {"id":"1","title":"post title 1","content":"post content 1.","comments":[{"comment":"comment 1 post 1."},{"comment":"comment 2 post 1."}]}, {"id":"2","title":"post title 2.","content":"post content 2","comments":[{"comment":"comment3 post 2."}]}, {"id":"3","title":"post title 3","content":"post content 3","comments":[]} ] When I run the code below, all the post records are displayed with some comment missing. Here is what I got [ {"id": 1, "title": "post title 1", "content": "post content 1.", "comment": {"comid": 4, "comment": "coment 4 for post 1"}}, {"id": 2, "title": "post title 2.", "content": "post content 2", "comment": {"comid": 3, "comment": "coment 3 for post 2"}}, {"id": 3, "title": "post title 3", "content": "post content 3", "comment": {"comid": 3, "comment": "coment 3 for post 2"}} ] My issues: Some comments are missing in the arrays For Instance: 1.) post with id 1 should have two comments in the array but am justing seeing one comment attached to the postid. 2.) Post with id 3 does not have any comment but am seeing comments attached to its postid I was wondering if this issue … -
How to serialize the result from select_related query in django
i want to join two tables using django select_related. But how can i serialize those data from two tables to get serialized details including full image url from another table My View.py class getALlUserProfileDataAPIView(views.APIView): permission_classes = (permissions.AllowAny,) def get(self, request): #usedraa = User.objects.filter(qs).select_related('userAddress').values('id','useraddress__country', 'useraddress__state', 'useraddress__city','email','username','first_name','last_name','password') usedraa = User.objects.filter().select_related('Profile').values('username','profile__image','first_name','last_name') #usedraa = User.objects.all().prefetch_related() userProfileSerializer0 = userProfileSerializer(usedraa, context={'request': request}, many=True) return Response(userProfileSerializer0.data, status=status.HTTP_201_CREATED) Serailizer ass userProfileSerializer(serializers.ModelSerializer): prodata = serializers.HyperlinkedIdentityField(read_only=True, view_name = 'profile') # prodata = ProfileSerializer(read_only=True, many=True) # many=True is required class Meta: model = User fields = ("first_name","last_name","username","prodata") -
Boto3 generating different links locally and on elastic beanstalk with a django application
I am a bit confused right now: I have a Django Application that uploads files to s3 and generates download links in the admin panel, to retrieve the files after uploading. I use boto3 for signing upload and download links. It all works fine locally but as soon as I deploy it to elastic beanstalk the links to download are not working anymore and it seems it generates the links with an old singing version. The upload still works though. I am generating the links like so: def downloadUrl(self): s3Client = boto3.client('s3') bucketName = getattr(settings, "AWS_STORAGE_BUCKET_NAME", None) fileurl = s3Client.generate_presigned_url('get_object', Params={'Bucket': bucketName, 'Key': self.url.split(bucketName + '/')[1]}, ExpiresIn=100) return format_html("<a href='{url}'>{url}</a>", url=fileurl) And the funny thing is it works locally and the generated links are different: Local Link: https://bucketname.s3.amazonaws.com/uploads/something/zips/2019/03/28/App%20Beschreibung.pdf.zip?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJNND443OXASGOY2Q%2F201330328%2Feu-central-1%2Fs3%2Faws4_request&X-Amz-Date=20190328T101414Z&X-Amz-Expires=100&X-Amz-SignedHeaders=host&X-Amz-Signature=4fe4d31dc1fd1f772217656654025b669513597c3f91f857fb722ff63a6c0194 Link Generated by Elastic Beanstalk Deployment: https://bucketname.s3.amazonaws.com/uploads/something/zips/2019/03/28/App%20Beschreibung.pdf.zip?AWSAccessKeyId=ASIA2K3XQKDHVDBX3GWN&Signature=w%2FWRh6tf%2Ba7k91Odop3ly9gEJDw%3D&x-amz-security-token=AgoJb3JpZ2luX2VjEHIaDGV1LWNlbnRyYWwtMSJIMEYCIQD7hU0fX24bksIM3vlQxZjYeje2sDm%2FQeeFQqUt7MwDpQIhAIozM1i1%2FmGK2Xo0RXmR7UWAB2FRPdkQy3aBOisS3BzuKuADCCsQABoMNzEwNTMwODQ2OTI3IgxfJIvFGgD5WL6TwccqvQO1Bsri%2FTmpvaARkFA%2BOnhLRUv9FFfdFf6H8W4IY38OI6CWzvct%2BgmE14D06GHaCh65wKH%2BhR9ZT3V18sW9U4RM%2FpS64hESmC8SUerzpPv9RmuXgA8hQl%2BwRJaTFLGFRFrHdHFoeJAeLIKjK2B7lDjLzNALtvegnLrBYoBtT0Ga2a7CC7avWMevvQ0jAjuSMiEOS4FjXNwHInkb%2FCrX3EXk2Me9OaufICHGH0ZTN2WNAGtOPsY15YJyLf0WgDl7SxVLuAnA4nUzeMglsdaL9ZbUlsdleJtHTQefNqCXXsm4FIup%2Fe%2FNFkn9g7XDH9%2F9IXW%2FNZyBAtfrRoPmDwvv0KpeYPpRpkVKBa5TxQU1c6ei3AiHnIQZRdO5oEqW47qv9hM8%2Fw9U9VlDqyUy5BKbGnv7GTLCdh4%2FwcYEnlfgr8QdK%2BJzyQYdgpMYqw3hj%2FTDW8mJVI9AD3RpHnD0XwIL3BBH5fUgcNZm2vGLG5nOcav7u2YaeqdFiY95SkdL5C8CLv%2BRLYABXyAbeWPUtFzgTtdUFFlv5epAQO2cPOD%2BM3V%2BjhfTQa4WUSIRCwUpSQg3dahIvV75cbKdsdZ7bL1tRMIqz8uQFOrMBC7isGac1kJ0TqHMbiQ77QauekC9c1gy6wgnKu9enc2x4VvyhClhvTvmEFm5NW3CmU5LIXf9V4Df9ML7Mf3Nf2uhuAhQdTKoAIGPiVWz%2FB3Lh%2F58%2FLbRbIRNgWk6IDg88dzgevitkXSC0OokmpB3qbBj%2BGXjIHttHqdBKnjG22aud3wrMk6YxH8b0CfelmcN5vHykpMYgdfgNHvFKrea417ozh5CLfZ9PYQoug0iqsm9nqoU%3D&Expires=1553768535 as you can see the signing is different but I do not understand why. I also checked if there is maybe a different version running on EB but it is the same version as locally, I downloaded the zip and ran it locally and it worked. -
Configure REDIS in Gitlab CI/CD for usage in Django
I had a working pipeline on GitLab which started failing after I added tests involving REDIS. I've applied (?) what is written inside GitLab docs but still REDIS is not discovered by my tests. Here's my gitlab-cy.yml file: pep8: image: python:latest services: - postgres:10-alpine - redis:latest variables: POSTGRES_DB: ci DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/$POSTGRES_DB" REDIS_URL: redis stage: test script: - python -V - pip install -r ./requirements/gitlab.txt - pytest --pep8 cache: paths: - ~/.cache/pip/ And here's how I'm using it inside Django: REDIS_URL = os.environ.get("REDIS_URL", "redis://localhost:6379/0") cache = redis.StrictRedis.from_url(url=REDIS_URL) I've also set Environment Variables inside CI/CD settings in GitLab REDIS_URL to redis however still when the test executes None gets assigned to host and the test fails ....-> self = Connection<host=None,port=6379,db=0> Any idea how to connect with Redis on GitLab? -
How do I implement Incoming webhooks?
I want to implement an Incoming webhook using Django and Django rest framework. If anyone has an idea of how to do it, please post-implementation in detail. -
how do i show user posts in one page and at the same time users can see others posts in their page? like the way facebook works?
I am creating a website which has a homepage where all users can see others posts and i want to allow users see their own posts in their profile and see other peoples posts when they visit their profile how do i do that? i have tried filtering the posts but the problem now is the logged in user is able to see his/her posts in his profile page but when he/she visits another user he sees hi own posts on that users page this is my views class ProfileView(TemplateView): template_name = 'Profile/Profile.html' #queryset = Posts.objects.all() @login_required def view_profile(self,request, pk=None): if pk: user = User.objects.get(pk=pk) posts = User.posts.objects.get(pk=pk) else: user = request.user #args = {'user': request.user} #if pk: posts = User.posts.objects.all().order_by('-date') return render(request,('Profile/Profile.html'), {'user': user , 'posts':posts }) def get(self, request, pk=None): #form = HomeForm() #posts = Post.objects.all().values('user') #order_by('-date') posts = Post.objects.filter(user=request.user.id).order_by('-date') users = User.objects.exclude(id=request.user.id) if pk: posts = Post.objects.get()#.order_by('-date') #user = User.posts.get(request, pk) else: user = request.user #friend = Friend.objects.get(current_user=request.user) #friends = friend.users.all() args = { 'posts': posts, 'users': users, } return render(request, self.template_name, args) this is my profile.html {% for post in posts %} <div class="row" style="width: 18rem; height:18rem; display:table-row" > <div class=" card border-grey row mb-3 shadow … -
Python versions, which one is better PyPy or Django?
I would like to improve my python skills and start writing scripts at a professional level. Currently, I'm using Python 2.7, I've done some research and realized that this version is not as fast as PyPy. Could anyone please give advice which version of Python is the most suitable for professional development? -
Django: sending email causes OSError
I'm setting up registration proces for my Django REST API. I use "email.send()" function in my SignUpView. When I create new user, it should send him activation link. Unfortunately i get "OSError: [Errno 99] Cannot assign requested address". I was looking for some solutions, but all was conected to some problems with sockets. Despite this I tried to change my ports in settings. My email settings in settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD= 'mypassword' EMAIL_PORT = 587 View i used to signup: class SignUp(APIView): def post(self, request, format=None): serializer = SignUpSerializer(data=request.data) if serializer.is_valid(): user = serializer.save(is_active=False) current_site = get_current_site(request) mail_subject = 'Aktywuj swoje konto w serwisie Podwoozka.' message = 'user: ', user.username,'domain', current_site.domain,'uid',urlsafe_base64_encode(force_bytes(user.pk)).decode(),'token', account_activation_token.make_token(user), to_email = user.email email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Potwierdz email aby zakonczyc rejestracje.') return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And finally entire Traceback when i use this function: Traceback (most recent call last): api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner api_1 | response = get_response(request) api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response api_1 | response = self.process_exception_by_middleware(e, request) api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response api_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) api_1 | … -
How to upload and view images in django
I'm new in Django .I need a help. How to upload images in database and view those images? Thanks in advance! here paths are stored in database and images are stored in folder.But i don't need that.I want to save images and path to database and i need to view that image.Please help! views.py: def uploadfile(request): print('inside upload logic') if request.method == 'POST': form = FileUploadForm(request.POST, request.FILES) if form.is_valid(): # ImageUpload(request.FILES['File_Name']) myfile = request.FILES['File_Name'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) newdoc = FileUpload(File_Name=myfile.name, File_path=uploaded_file_url, Description=request.POST['Description']) newdoc.save() #return HttpResponse("File uploaded successfuly") return render(request, 'Login/fileupload.html') else: form = FileUploadForm() return render(request, 'Login/fileupload.html', { 'form': form }) -
i tried this code by i am having problem to save data in mysql database
i am creating e-commerce application using django i tried all things by i can not insert data in mysql database i already tried using mysql query and forms as well. demo.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <form method='POST' action="/demo"> {% csrf_token %} <div class='main'> <label>Full Name</label> {{ form.fname }} <label>UserName</label> {{ form.uname }} <label>Email</label> {{ form.email }} <label>mobile</label> {{ form.mobile }} <label>Password</label> {{ form.password }} <button type="submit">Click me!</button> </div> </form> </body> </html> model.py class new_table(models.Model): fname = models.CharField(max_length=50) uname = models.CharField(max_length=50) mobile = models.IntegerField() email = models.CharField(max_length=50) password = models.CharField(max_length=50) class Meta: db_table = 'new_table' views.py def demo_action(request): if(request.method == 'POST'): form = NewTableForm(request.POST) if form.is_valid(): try: form.save() return redirect() except: pass else: form = NewTableForm() return render(request,"demo.html",{'form':form}) forms.py class NewTableForm(forms.ModelForm): class Meta: model = new_table fields = "__all__" i am creating e-commerce application using django i tried all things by i can not insert data in mysql database i already tried using mysql query and forms as well. -
Logical constraint in Django - need logics
Now this problem I am facing currently is having constraints. Let me explain what sort of constraints I am talking about, I am working on a survey application that is built on Django 2x, The survey that my project creates are simple questions, but I want to add constraints in a sense that when a question A is asked with options a, b. If the answer for question A is a then I should get question B or if the answer is b then I should get question C. Now the problem is I cannot have if-else-elif conditioning written there for this purpose as the data (questions and options) are coming dynamically, like on runtime!