Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to verify account by passing token to the email and user will enter it
In django when some one signup for new account, he will be sent an email with an activation link. One has to click on the activation link sent to them to activate their account. This i was able to achieve using Django. Presently I am developing a mobile app. I feel instead of asking them to click on an activation link, i want them to enter some code inside the app. The code will be sent to their email. So how to verify the account by passing token and later user will enter it. -
Can i make a form consisting of different fields with signup fields?
models.py class employeeModel(models.Model): employee_id = models.CharField(max_length=300,unique=True,help_text='Employee ID should not be same') name = models.CharField(max_length=300) father_name = models.CharField(max_length=300) username = models.CharField(max_length=50,null=True,blank=True) email = models.EmailField(null=True,blank=True) password = models.CharField(max_length=20,null=True,blank=True) def get_absolute_url(self): return reverse('detail_view',kwargs={'employee_id':self.employee_id}) def __str__(self): return self.employee_id class Meta: verbose_name = 'Employee Detail' views.py User = get_user_model() def create_view(request): if request.method == 'POST': form = employeeForm(request.POST or None,request.FILES or None) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] User= get_user_model() user= User.objects.create_user( username=username,email=email,password=password ) authenticate( request,username=username,email=email,password=password ) user.save() form.save() return redirect('emp_list') else: form = employeeForm() return render(request,'create_employee.html',{'form':form}) Though its not raising any error but User cant create instances though this method, though 'user objects' are showing in EmployeeModel.objects.all() not in User.objects.all(). Thats why when i create any user though this form login fails cause they are not objects of User. What can i do to make it work? or i have to discard this code? -
How to create the related field?
I have a Model you see bellow: class PriceModel(models.Model): name = models.CharField(max_length=12) the PriceModel's id is increased from 1. I want to add other field, which is related to the id. Such as I want it to #PM1, #PM2... means the #PM + id. How to create the related field? -
How can I edit the related other factor `id`?
I have a User model, which generated the bellow table: in it the id is increase from 1. I have used my system in a spell, now I want to change the id of some user instance. in the database I can not change, it will report error: Cannot delete or update a parent row: a foreign key constraint fails (`qy`.`usermanage_user_groups`, CONSTRAINT `usermana_user_id_53f44f10_fk_qy_adm` FOREIGN KEY (`user_id`) REFERENCES `usermanage_user` (`id`)) Is it possible to change the id? if there is some related factors, how can I solved it one by one, such as usermanage_user_groups? -
Register multiple tasks with Celery
I'm building a simple helper class for sending emails in Django and Celery. My code import logging from celery import Task from django.conf import settings from django.core.mail import send_mail from render_block import render_block_to_string from optilimo.celery import app from reservations.models import Reservation logger = logging.getLogger(__name__) class Mailer(Task): """ Build emails from template and send them via Celery. Includes some helper functions as well. """ template = None from_email = settings.DEFAULT_FROM_EMAIL name = 'mailer' max_retries = 3 def build_context(self, ctx): return ctx def run(self, to_email, ctx, *args, **kwargs): ctx = self.build_context(ctx) subject = render_block_to_string(self.template, 'subject', ctx) plain = render_block_to_string(self.template, 'plain', ctx) html = render_block_to_string(self.template, 'html', ctx) send_mail(subject, plain, self.from_email, [to_email], html_message=html) logger.info('Email sent to {}'.format(to_email)) def on_success(self, retval, task_id, args, kwargs): super(Mailer, self).on_success(retval, task_id, args, kwargs) logger.info('Email with task ID {} was successfuly sent.'.format(task_id)) def on_failure(self, exc, task_id, args, kwargs, einfo): super(Mailer, self).on_failure(exc, task_id, args, kwargs, einfo) logger.error('Email with task ID {} was failed to send.'.format(task_id)) logger.error('Error: {}'.format(str(exc))) class QuoteRequestMailer(Mailer): template = 'mails/internal/quote_request.html' class ReservationDetailsMailer(Mailer): template = 'mails/internal/reservation_details.html' def build_context(self, ctx): reservation = Reservation.objects.first() return {'reservation': reservation} app.tasks.register(QuoteRequestMailer) app.tasks.register(ReservationDetailsMailer) Problem When I register more than one task (for example in the code above), the last task registered get's called no matter what … -
Redirect from django admin list on filter list
In django 1.11, my problem is, how can I redirect from admin url below: http://127.0.0.1:8000/admin/events/event/ automaticly to: http://127.0.0.1:8000/admin/events/event/?date__gte=2018-01-01&date__lt=2019-01-01 Please some hint. -
why is my pdf not showing in django template?
I am trying to display a pdf file in an html template and also be able to update that pdf file, I read the tutorials on how to display a pdf file but I'm not sure why mine isn't really working, I have a model called Reference class References(models.Model): REFERENCE_MATERIAL = ( ('seating', 'Seating Plan'), ('organization', 'Organization Chart') ) # the variable associated with the reference reference_name = models.CharField(max_length=100, choices=REFERENCE_MATERIAL,) reference_file = models.FileField(null=True, blank=True, upload_to='references/') date_updated = models.DateField(auto_now=True) # on submit click of update entry page, it redirects to the url below. def get_absolute_url(self): return reverse('references-home') Here are the views to update a reference and the one that displays it class SeatingReferenceView(generic.ListView): context_object_name = 'seating_plan' template_name = 'catalog/references-seating.html' def get_queryset(self): return References.objects.filter(reference_name='seating').order_by('date_updated').first() def reference_update(request): if request.method == 'POST': form = UploadReference(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect('references-home') else: form = UploadReference() return render(request, 'catalog/references_update.html', {'form': form,}) However I'm receiving nothing in my html template, I can see in my database that under the reference_file column that there are files called seatingplan.pdf but still nothing is showing. Thank you ! -
How do i access Django Model object in another view?
I have a code like this: def my_view(request): # ... data=Data.object.create(xyx) data.id // here data.id=20 time.sleep(180) //here sleep 180 sec # within 3 min how can i get data oject in another view. return HttpResponse("Done") Ques. How can i get data object that belogs to id= 20 in anohter view before return HttpResponse (Means with in 3 min). I'm getting data.models.DoesNotExist I think becouse of Data object not committed on the database. Thanks in advance. -
Ajax goes to url instead of changing data Django
I'm using ajax in Django to activate add to favorites button, here are my files urls path('<int:pk>/favorite_item/', views.favorite_item, name='favorite_item'), views.py @login_required def favorite_item (request, pk): favitem = get_object_or_404(Item, pk=pk) data = { 'is_fav': Favorite.objects.filter(user=request.user, item=favitem).exists(), } if data ['is_fav']: Favorite.objects.get(user=request.user, item=favitem).delete() else: new_entry = Favorite.objects.create(item=favitem, user=request.user) return JsonResponse(data) finally HTML only the part of the script {% block javascript %} <script> $("#add_to_fav").click(function () { console.log( $(this).val() ); }); $.ajax({ url: form.attr("data-favorite_item-url"), data: form.serialize(), dataType: 'json', success: function (data) { $('.results').html(data); }, }); </script> {% endblock %} Now when I click the element that should trigger the whole action, the function is already working and the item is removed or added to db, but it takes me to another page which only has 1 sentence ({"is_fav": true}) or ({"is_fav": false}) -
Callback URL for the API Response Django
I am building a code editor using the Hackerearth API.I have made the code to send a asynchronous API Request as it would speed up performance and reduce waiting time. I referred their docs about sending an async request.I need to specify a callback url.Currently my project is running locally.So I couldn't figure out how to specify the callback URL and render out the Response from that callback URL.The logic to process the response received at the callback url is also specified in their docs. def compileCode(request): if request.is_ajax(): source = request.POST.get('source') lang = request.POST.get('lang') client_secret = settings.CLIENT_SECRET data = { "client_secret": client_secret, "async": 1, 'id': 123, 'callback': **what to do here**, "source": source, "lang": lang, } res = requests.post(RUN_URL, data=data) return JsonResponse(res.json(), safe=False) return HttpResponseBadRequest() Code to process the Response from the callback URL def api_response(request): payload = request.POST.get('payload', '') payload = json.loads(payload) run_status = payload.get('run_status') o = run_status['output'] return HttpResponse('API Response Recieved!') Any help is welcome :) -
Celery discovers all tasks even when `app.autodiscover_tasks()` is not called
I am using Django==2.0.5 and celery==4.0.2. My proj/proj/celery.py looks like: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj', include=[]) # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. # app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) I was expecting that none of the tasks decorated with shared_task in tasks.py of the apps will be discovered but to my surprise, most of the tasks can be seen under [tasks] when running celery worker with celery worker -A proj -l INFO. Any suggestion is welcome. -
How to add a custom popup on django admin page in the change view section?
def comments(self, obj): return format_html('<a class="button" href="{}?_popup=1">Add Comment</a>', reverse('admin:create-leadcomment', args=[obj.pk])) I want this link to open in a new popup window. -
Defer rendering of Django template tag
I'm porting an old PHP project over to Django. In this project ads are being displayed using javascript. For this I've written a template tag that generates (using a template) the appropriate code. However, in the HTML head tag of the page a list of all ads should be generated to preload these ads. The problem is that the head tag is generated in a base template, which is rendered before the actual page contents. At that time of rendering the list of rendered ads is not yet known. Searching the web I've found two possible solutions (honestly I'm a bit amazed that nothing further popped up in my searches, although that can easily be blamed to bad google-fu skills...): https://django-sekizai.readthedocs.io/en/latest/ This seems to be the most elegant solution, but is only supported to Django 1.10 (I'm using 2.0). It also is restricted in where the template tags can be used, which is a major problem for me (specifically: I would need to use the render_block tag in an if-statement, which is not possible). https://github.com/codysoyland/django-phased In this solution the template is rendered twice. The list of rendered ads would then be generated on the first pass, and so the generation … -
'Questions' object has no attribute 'strip'
I am trying to give the post an audio by gTTS method. while doing this audio work on this post, i am getting the error 'Questions' object has no attribute 'strip'. def qpage(request): contact_list = Questions.objects.all() paginator = Paginator(contact_list, 1) # Show 25 contacts per page page = request.GET.get('Q') contacts = paginator.get_page(page) spk = Questions.objects.get(id=page) tts = gTTS(text=spk, lang='en') tts.save("pcvoice.mp3") os.system("start pcvoice.mp3") return render(request, 'data/quit.html', {'contacts': contacts}) -
Processing a webhook with the microsoftgraph API and Django
I'm currently developing a simple web app that connects to an Outlook 365 account through the Microsoft Graph API. In this app, I'd like to set up a webhook that processes emails upon their reception in the inbox. However to do so, I need to retrieve a token in order to process the email. Here is my current Django code : @csrf_exempt def webhook(request): validation_token = str(request) validation_token = validation_token.replace( "<WSGIRequest: POST '/app/webhook/?validationToken=", "") validation_token = validation_token.replace( "HTTP/1.1", "").replace("'>", "") if len(request.body) == 0: request.session['validation_token'] = validation_token return HttpResponse(validation_token, content_type="text/plain") else: data = json.loads(request.body) print('received notification(s) !') notifications = data['value'] request.session['notifications'] = notifications return HttpResponseRedirect(reverse('app:categorize'), status=202) The categorize view (in views.py), which I'm redirecting to, is supposed to handle the incoming notification (message reception or update). The reason I'm not handling it in the webhook view is because I need to renew a token that should already be stored in the session object. However perhaps maybe because request is an incoming POST query, the token isn't stored in the session. def categorize(request): access_token, refresh_token, expiration = get_access_token( request, request.build_absolute_uri(reverse('app:gettoken'))) notifications = request.session.get('notifications') if notifications is not None: account = OutlookAccount( access_token=access_token, refresh_token=refresh_token, token_expiration=expiration ) for resource in notifications: resource_data = … -
Django validate AuthenToken Manually in a Serializer
So I have an app where I can book rooms. But I want to validate the user when he books a Room. I know that I can do that with the obtain_auth_token function. But I want to Validate the user myself with the token. So i am saving the token into the user when the user login to the site, and when the user want to book a room I'll give a token as a parameter to the booking view/serializer. Now I want to validate this token send with the booking request. Here is what my Serializer look like: class BuchungSerializer(ModelSerializer): """Serializer to map the Model instance into JSON format.""" token = serializers.CharField(required=True, allow_blank=False, write_only=True) class Meta: """Meta class to map serializer's fields with the model fields.""" model = Buchung fields = ['id', 'user', 'time_choices', 'raum', 'platz', 'datum', 'token'] related_fields = ['user', 'raum', 'platz'] extra_kwargs = {"token": {"write_only": True}} username = serializers.CharField(source='user.username') def validate_token(self, value): user = Mitarbeiter.objects.filter(Q(username = username)) if user.exists() and user.count() == 1: user_obj = user.first() user_token = user_obj.usertoken token = Token.objects.get(key=value) if token == user_token: return value else: raise ValidationError("Token not Valid") else: raise ValidationError("User doesn't exist") def create(self, validated_data): reservation = Buchung( user=validated_data['user'], time_choices=validated_data['time_choices'], raum=validated_data['raum'], … -
How to Convert this coordinates to Latitudinal's and longitudinal's in Python?
{ "type": "MultiPolygon", "coordinates": [[[ [6707794.77817316, 1952512.97762237], [6707794.43138905, 1952566.21209599], [6707897.49942442, 1952567.26754007], [6707897.9039513, 1952513.5347079], [6707794.77817316, 1952512.97762237] ]]] } I am very new to GeoDjango. These are my Geojson coordinates. These are the Coordinates for Parcel data that belongs to Sacramento City. How to convert these coordinates into Lat Long in Python -
how to point to wsgi file in changed django project layout - django
I've changed my Django project layout. now it looks like: in /home/myuser/ i have a folder named myproject and inside of this folder there are two folders: env and site. and the site folder layout is like below: `+ apps -- accounts -- mainp -- business + config -- wsgi.py -- urls.py ++ settings -- base.py -- prod.py -- local.py the problem is with gunicorn systemd file. this is its content: [Unit] Description=gunicorn daemon After=network.target [Service] User=myuser Group=www-data WorkingDirectory=/home/myuser/myproject ExecStart=/home/myuser/myproject/env/bin/gunicorn --access-logfile - --workers 4 --bind unix:/home/myuser/myproject/site/site.sock site.config.wsgi:application [Install] WantedBy=multi-user.target when i reload and after that restart gunicorn after sudo systemctl status gunicorn, I see this error: Jun 11 16:11:04 site gunicorn[13589]: ImportError: No module named 'config' Jun 11 16:11:04 site gunicorn[13589]: [2018-06-11 16:11:04 +0430] [13600] [INFO] Worker exiting (pid: 13600) Jun 11 16:11:04 site systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Jun 11 16:11:04 site systemd[1]: gunicorn.service: Unit entered failed state. Jun 11 16:11:04 site systemd[1]: gunicorn.service: Failed with result 'exit-code'. what's the problem? and how can i solve it? -
Django admin panel customization for uploading and downloading pdf files
I basically want to implement a functionality in Django admin panel wherein, there will be an option to upload a pdf file and that pdf file will be directly stored to sqlite db (not on a local directory). Also, if I click on the file it should download automatically or atleast get displayed in the browser. How can I achieve this? -
Django How to reference a field from a class A from which a foreignkey has been declared by nother class B
I am still not satisfied with django foreignkey relationship. below are two classess a top class A, and a bottom class B. class A(models.Model): title = models.CharField(max_length=25,unique=True) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='image_uploader') slug = slug = models.SlugField(allow_unicode=True,unique=True) class B(models.Model): title = models.ForeignKey(A,related_name='post_title' image = models.ImageField(upload_to='gallery_pics', verbose_name='Image') In views.py lets say i want to get slug from class B(models.Model): How will i do it? def allImages(request,slug): picture = get_object_or_404(A, slug=slug) While i perfectly know that Class B has no field by the name slug though there is a foreign key. How will i get the slug from Class B. The codes are just samples for demonstration.please somebody help me. -
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-lif26x4i/mysqlclient/
Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/6f/86/bad31f1c1bb0cc99e88ca2adb7cb5c71f7a6540c1bb001480513de76a931/mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-lif26x4i/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/tmp/pip-install-lif26x4i/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/tmp/pip-install-lif26x4i/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found -
django anonymous user session data saved after user login
i was writing small ecommerce application in django framework. so i was trying to implement add to cart functionality like that if user is anonymous user then selected products should be mapped to it's session id which is act. cart id in models. so the scenario is that whenever anonymous user check out and mapped data against that session id is purged. Is there any mechanism to save anonymous user session data even after user logs in. kindly provide easy possible solution as i am bit new to django:) Thanks, Siddharth -
Multiple Django apps with each having a react frontend
I have a Django aplication (+REST framework) with pluggable Django apps (which are discovered using distutils' entry points, and can be developed independetly from each other, and installed via pip). This works well so far. The main app should provide a basic index.html with a React frontend, and each app should be possible to add React components "to the mix", on the client side. But: How the heck am I supposed to place my client directories into each app, so that they are found for collecting all the static files? Should I put a react app into /my-app1/client and /my-app2/client? And tell Webpack/brunch/whatever to compile all the css/js etc files into /my-app1/static, followed by ./manage.py collectstatic then? Is there a better approach to collect distributed react "plugin" in dfferent Django apps into one static directory? Can brunch.io do this? Webpack? Another? Own script? It would be nice to have something like brunch watch - to have hot-updated all changed files instantly. This works for one directory, but not for a distributed net of plugin directories, right? Or is this completely thought wrong? Please help. -
Easy to use Python based CMS tool
I am required to build a Image based CMS tool for a company for internal operations. The CMS should have functionalities like uploading set of images of products and browsing for those images like popular searches, customised search, all products etc. I have been trying to do that using Django from couple of weeks but never progressed much. I have been facing problems with dynamic multiple upload(since django doesn't allow that dynamically, I had tried using jQuery-File-Upload plugin and JS) and querying the database to view the images. Since my deadline is day after tomorrow and I have no tech support in my company, I am asking for help in this StackOverflow community. Is there any free easy to customise open source CMS tool which is Python based? Or any other advice to this noob programmer to be able to finish before the deadline? -
How to read a file using tensorflow which is uploaded by django
I have uploaded a file using django & django rest framework,an that image we have InMemoryUploadedFile. Now I want to read this file using tensorlfow. serializers.py class ImageClassificationSerializer(serializers.Serializer): image = serializers.ImageField() views.py class ImageClassificationView(APIView): parser_classes = (MultiPartParser, FormParser) serializer_class = ImageClassificationSerializer def post(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): input_name = "file_reader" file_reader = tensorflow.read_file(serializer.validated_data['image'], input_name) print file_reader response = { "success": True } return Response(response, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) when I am reading file, I am geeting below mentioned error : Expected string passed to parameter 'filename' of op 'ReadFile', got <InMemoryUploadedFile: mobile_image.jpeg (image/jpeg)> of type 'InMemoryUploadedFile' instead.