Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Url routing breaks in VSCODE, works fine on atom if built from scratch.Why?
I built a basic Django project from scratch in Vscode , Here is the Link : https://hastebin.com/levogipiqa.xml But the name = attribute in urls.py always fails if I change count/ to anything else , even with the name argument included. What's weird is if I build the same project from scratch in Atom all is well, and the error goes away. Pylint is enabled on Vscode, no linting tools in Atom. Error Message : Using the URLconf defined in WordCounter.urls, Django tried these URL patterns, in this order: countsddfdf/ [name='shit'] The current path, countsd/, didn't match any of these. -
Retrieve custom variable from PayPal Button in Django
Hi I have a django app hosted on Heroku. I have a view with the paypal button, which is working and sends me back to my success url. But on the success url I want to display/use my custom variable. I tried some solutions from StackOverflow already, but I can not fix it by myself. URLS path('match/<int:pk>', MatchDetail, name='match-detail'), path('match_paid/', MatchPaid, name='match-paid'), MatchDetail - PayPalButton The form looks like this: <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top"> <input type="hidden" name="cmd" value="_s-xclick"> <input type="hidden" name="hosted_button_id" value="..."> <input type="hidden" name="custom" id="custom" value="{{match.id}}"> <input type="image" src="https://www.sandbox.paypal.com/de_DE/DE/i/btn/btn_paynow_LG.gif" border="0" name="submit" alt="Jetzt einfach, schnell und sicher online bezahlen β mit PayPal."> <img alt="" border="0" src="https://www.sandbox.paypal.com/de_DE/i/scr/pixel.gif" width="1" height="1"> </form> In PayPal I have set the custom variables of my button to: custom=custom # What is most likely wrong. Now I want the custom variable to be print in the return URL 'match_paid/'. Tried {{custom}}, {{request.custom}} etc. -
save time and render it for user selection
I have a form for bus timetable. Where bus stops at station A at 12:00,13:00,14:00,15:00 and goes on. station B at 12:15,13:15,14:15,15:00 and goes on. station C,D,E,F....and goes on. Each bus has a start time and Finish time and intervals of 15 or 30 or 45 or 60 minutes. How can I store the start time, end time and intervals in the database and render it on the form? we want the user to select only from the available times. -
python django - query returns blank result if searched agains mutiple column values for multiple rows and a few rows do not exist
I have a list namely ids_foundthat has a few values. These values are the primary keys in the database table news. If all the corresponding rows exist in the table, then I get the expected result i.e. ids_found_result. But if any of them is missing, the result becomes just an empty list. The code follows here: ids_found=[2,3,34] ids_found_result=[] clauses = ' '.join(['WHEN id=%s THEN %s' % (pk, i) for i, pk in enumerate(ids_found)]) ordering = 'CASE %s END' % clauses ids_found_result = news.objects.filter(pk__in=ids_found).extra( select={'ordering': ordering}, order_by=('ordering',)) ids_found_result = list(ids_found_result) How can I make it to produce the result when one or more rows are missing in the database ? If n number of rows are missing then the expected result should be the ids_found_result containing elements less by n. -
Django querying many to many relations
I have 3 models: group, word, phrase As you can see word belongs to group and there is a many to many relation between phrases and words: class Group(models.Model): name = models.TextField() class Word(models.Model): group = models.ForeignKey(Group, on_delete=models.SET_NULL, null=True, related_name = "words") class Phrase(models.Model): words = models.ManyToManyField(Word, null=True,related_name = "phrases") name = models.TextField() And right now I need to find all phraseswith name ="xxx" that have at least one word from group with group id = '177' How do I do this? -
Inline formset returns empty list on save?
When I try to save my inline formset it just returns an empty list and no changes are reflected in the database. I have tried doing it with no option and commit=False but they both have the same result. I know there is data because I printed the formset as a table, and I know it is valid because the property is_valid() method returns true. Here is the code: def edit(request): if request.method == 'POST': print(request.POST) form = TombstoneForm(request.POST) print(form.is_valid()) t = form.save(commit=False) t.edit_date = datetime.now() t.user_editor = request.user t.save() print(t) formset_construct = inlineformset_factory(Tombstone, Tank, form=TombstoneForm) formset = formset_construct(request.POST) print("Passed the inline formset") print(formset.as_table()) print(formset.is_valid()) l = formset.save() print(l) return render(request, 'main.html') -
How can I run Django unit test in Microsoft TFS automatically?
How can I run django unit test in Microsoft TFS automatically? -
How to upload to imagefield in Django
I can create my objects in Django Framework and upload images directly from there. Now I want to upload image from an HTML form and no more from Django Framework. How can i upload image from my HTML to my /media/ folder? my models.py: class New(models.Model): news_title = models.CharField(max_length=100,blank=False,verbose_name="Titolo news") news_small_description = models.TextField(default=None,null=True,blank=True,verbose_name="Descrizione breve") news_description = models.TextField(default=None, null=True, blank=True, verbose_name="Descrizione") news_image = models.ImageField(default=None, blank=True, null=True, verbose_name="Immagine") news_date = models.DateTimeField(auto_now=True, null=True, verbose_name="Data news") class Meta: verbose_name = "New" verbose_name_plural = "News" my view.py POST API: @api_view(['POST']) def send_news(request): try: newstitle = get_param(request.POST, "newstitle", NOT_NONE) newssmalldescription = get_param(request.POST, "newssmalldescription", OPTIONAL) newsdescription = get_param(request.POST, "newsdescription", OPTIONAL) newsimage = get_param(request.POST, "newsimage", OPTIONAL) New.objects.create( news_title = newstitle, news_small_description = newssmalldescription, news_description = newsdescription, news_image = newsimage, ) return HttpResponse("La tua novitΓ Γ¨ stata aggiunta correttamente.") except ValueError as ve: print(ve) return HttpResponseBadRequest(json.dumps({"error_message": str(ve)}), content_type='application/json') except Exception as e: print(e) return HttpResponseServerError(json.dumps({"error_message": str(e)}), content_type="application/json") In my html i send a POST request to my send_news API and the only missing field is the newsimage. But i can't understand how can i charge a pic from my HTML page to my MEDIA folder. Thank you! -
Django postgres constraint EXCLUDE WITH GIST
I created a time field as follows: start_date = models.DateField() end_date = models.DateField() When trying to create a constraint on the table with ALTER TABLE analytics EXCLUDE USING gist (campaign WITH =, tstzrange(start_date, end_date) WITH &&) I get an error ERROR: functions in index expression must be marked IMMUTABLE Does anyone know how to fix this issue? -
Django, Haystack, Elasticsearch: Rejecting mapping update to ...
... [transcription-index] as the final mapping would have more than 1 type: [doc, modelresult] I get the above error on a completely clean Django (i.e. deleted all former migrations and sqlite.db). Elasticsearch is 6.2.4, elasticsearch_dsl is 6.1.0 and Django is 2.0.5. Then I run python manage.py makemigrations and python manage.py migrate which works fine. Following python manage.py createsuperuser I can log in, and have a look at http://127.0.0.1:8000/admin/elasticsearchapp/transcription/ which is empty, but has all the correct fields (identifier, speaker, title, description, trans). My problem comes when I try to populate my sqlite.db with data by running python manage.py populate, I get raise BulkIndexError('%i document(s) failed to index.' % len(errors), errors) elasticsearch.helpers.BulkIndexError: ('1 document(s) failed to index.', [{'index': {'_index': 'transcription-index', '_type': 'modelresult', '_id': 'elasticsearchapp.transcription.1', 'status': 400, 'error': {'type': 'illegal_argument_exception', 'reason': 'Rejecting mapping update to [transcription-index] as the final mapping would have more than 1 type: [doc, modelresult]'} Full traceback is found below. Code: search_indexes.py: from haystack import indexes from elasticsearchapp.models import transcription class transcription_index(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField( document=True, use_template=True) identifier = indexes.CharField(model_attr='identifier') speaker = indexes.CharField(model_attr='speaker') title = indexes.CharField(model_attr='title') description = indexes.CharField(model_attr='description') trans = indexes.CharField(model_attr='trans') def get_model(self): return transcription def index_queryset(self, using=None): return self.get_model().objects.all() search.py: from elasticsearch_dsl.connections import connections from elasticsearch_dsl β¦ -
Run several cmd command from batch(.bat) file
Scenario: I'm developing a project in python and DJango. Every time I need to activate my virtual environment and then run webserver. what i do is as follows.. run cmd then enter the following command C:\Users\azad>e: E:>cd E:\Development\Python\djangogirls E:\Development\Python\djangogirls>dgvenv\Scripts\activate this command activate my virtual environment and change my working directory(command prompts) (dgvenv) E:\Development\Python\djangogirls>python manage.py runserver Now I want to create a windows batch(.bat) file so that I can do the above task with one click. If I could not make a sense please reply me. thanks in advance. -
make /one/{id}/two in django rest
models.py class One(models.Model): hav = models.CharField(max_length=10) nat = models.CharField(max_length=34) class Two(models.Model): seti = models.CharField(max_length=45) raj = models.CharField(max_length=20) one = models.ForeignKey(One) serializers.py class OneSerializer(serializers.ModelSerializer): class Meta: model = One fields = '__all__' class TwoSerializer(serializers.ModelSerializer): class Meta: model = Two fields = '__all__' views.py class OneViewSet(viewsets.ModelViewSet): serializer_class = AppointmentSerializer queryset = One.objects.all() class TwoViewSet(viewsets.ModelViewSet): serializer_class = TwoSerializer queryset = Two.objects.all() I have two seperate views for One and Two. So, I need to give 2 urls ie. /one/ and /two/. How can I make single or many views(if necessary) to make two work on single url like /one/{id}/two/. What are the possible ideas? Plz help. -
In Django DRFs' `ListCreateAPIView` POST method, how do we get the pk of a model field?
I have a simple ModelSerializer which looks like this: class DBaaSOrderSerializer(serializers.ModelSerializer): class Meta: model = DBaaSOrder fields = '__all__' The above has also some validate methods which are not relevant for this question. Now, I'm using the above serializer in a Class-Based View like this: class DBaaSOrderView(generics.ListCreateAPIView): serializer_class = DBaaSOrderSerializer permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): usd = UsdDBActions() orders = DBaaSOrder.objects.filter(user=self.request.user).order_by('updated_at') for change_ref, change_status, updated_at in orders.values_list('change_ref', 'change_status', 'updated_at'): usd_change_status = usd.get_rfc_status(change_ref) usd_change_updated_at = usd.get_last_mod_date(change_ref) if change_status != usd_change_status: orders.filter(change_ref=change_ref).update(change_status=usd_change_status) if updated_at != usd_change_updated_at: orders.filter(change_ref=change_ref).update(updated_at=usd_change_updated_at) return orders.filter(change_status__in=VALID_USD_STATUSES)[:MAX_ORDERS] @staticmethod def get_dns(value): dns_records = DNS.objects.all() for dns in dns_records: if dns.server in value and dns.domain in value: return dns @staticmethod def get_backup_plan(value): backup_plans = BackupPlan.objects.all() for backup_plan in backup_plans: if backup_plan.customer_policy_name in value and backup_plan.retention in value: return backup_plan def post(self, request, *args, **kwargs): data = request.data data['user'] = request.user.pk dns_record = self.get_dns(data['dns']) backup_plan = self.get_backup_plan(data['backup']) dns_record_pk = dns_record.pk backup_plan_pk = backup_plan.pk data['dns'] = dns_record_pk data['backup'] = backup_plan_pk serializer = DBaaSOrderSerializer(data=data) if serializer.is_valid(): usd = UsdDBActions() data = request.data usd_data = { 'organization': int(data['organization_pk']), 'category': 'SSC.DBM.DB.ADD', 'assignee': request.user.username, } response = usd.create_rfc(usd_data) try: result = response.json() if result['code'] == 200: change_ref = int(response.json()['reference_number']) data['user'] = request.user data['change_ref'] = int(response.json()['reference_number']) data['change_status'] = usd.get_rfc_status(change_ref) β¦ -
How to add a custom tag/filter to an existing Django app?
I have to adapt a Django application (first time working with Django) and I'm running into issues getting a custom tag/filter to work. The app I'm working with has the following structure: tool |- manage.py |- templates |- ... |- vote |- initadmin |- initproc |- templatetags | __init__.py | guard.py |- __init__.py |- apps.py |- models.py |- views.py |- __init__.py |- urls.py |- settings.py |- __pycache__ |- wsgi.py In settings.py my installed apps contains: INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', # 3rd party ... # must be before admin ... 'django.contrib.admin', # locally 'vote.initadmin', 'vote.initproc', ] I wanted to add a custom tag, which I could load from within templates {% load site_defaults %} to add certain default parameters to templates. From the docs I understand, that I would have to: 1) add a module to templatetags, so I created # /vote/initproc/templatetags/site_defaults.py import os from django.conf import settings from django import template from six.moves import configparser site_parser = configparser.ConfigParser() site_parser.read(os.path.join(settings.BASE_DIR, "init.ini")) register = template.Library() @register.filter(name='site_defaults') def get_setting(my_setting): return site_parser.get("settings", my_setting) 2) Load this in a template and call my method, for example: {% load static %} {% load i18n %} {% load site_defaults %} <!DOCTYPE β¦ -
AttributeError| Model object has no attribute 'get'
This is my model class Leave_Management(models.Model): employee = models.ForeignKey('employeeModel', on_delete=models.CASCADE) name = models.CharField(max_length=50) reason = models.TextField(max_length=200) date_to = models.DateField(null=True) date_from = models.DateField(null=True) leave_balance = models.IntegerField(default=14) paid_leave = models.IntegerField(default=0) unpaid_leave = models.IntegerField(default=0) time_generated = models.DateTimeField(auto_now_add=True) time_approved = models.DateTimeField(null=True, blank=True) def get_absolute_url(self): return reverse('approve',kwargs={'pk':self.pk}) def __str__(self): return str(self.employee) def get_total_days(self): dt = (self.date_to - self.date_from).days return dt I have created two instances of above model. So when i try to access those instances in Django Shell it works fine >>> form = Leave_Management.objects.all().get(pk=1) >>> form <Leave_Management: Emp001> But when i try such thing in views.py It raises error that E Exception Type: AttributeError Exception Value: 'Leave_Management' object has no attribute 'get' views.py def approve(request,pk): form = Leave_Management.objects.get(pk=pk) return form Is there anything wrong in my views.py? -
Django Error django.db.utils.IntegrityError: FOREIGN KEY constraint failed
It worked earlier, i received this one after running the import etc. Do you know why i got this? How should i change my models. i recall that Django is doing authomaticaly the foreign key in the backend. Can you please advise how is better to do this? The DB exists, the model exists, i did the migrations and migrate also. These are my models: from __future__ import unicode_literals from django.db import models # from django.core.urlresolvers import reverse from django.urls import reverse # Create your models here. class Ofac_Sdn(models.Model): number = models.IntegerField(blank=True, null=True) name = models.CharField(max_length=200, null=True) b_i = models.CharField(max_length=250, null=True) programe= models.CharField(max_length=250, null=True) more_info = models.CharField(max_length=250, null=True) vessel_call_sign = models.CharField(max_length=250, null=True) vessel_type= models.CharField(max_length=250, null=True) vessel_dwt = models.IntegerField(blank=True, null=True) # vessel_dwt = models.CharField(max_length=250,blank=True, null=True) tonnage = models.IntegerField(blank=True, null=True) vessel_flag = models.CharField(max_length=250, null=True) vessel_owner= models.CharField(max_length=250, null=True) dob_aka= models.CharField(max_length=250, null=True) date_of_creation = models.DateTimeField(max_length=250, auto_now=True,blank=True, null=True) publish_date = models.DateTimeField(max_length=250, auto_now_add=True,blank=True, null=True) #content = models.TextField(blank=True, null=True, default="") class Meta: verbose_name_plural = "ofac_sdn" def __str__(self): return ((self.number, self.name, self.programe)) class Ofac_Add(models.Model): number = models.ForeignKey(Ofac_Sdn, on_delete=models.CASCADE) n= models.IntegerField(blank=True, null=True) adresa = models.CharField(max_length=250, null=True) oras_zip = models.CharField(max_length=250, null=True) stat = models.CharField(max_length=250, null=True) ceva = models.CharField(max_length=250, null=True) date_of_creation = models.DateTimeField(max_length=250, auto_now=True,blank=True, null=True) publish_date = models.DateTimeField(max_length=250, auto_now_add=True,blank=True, null=True) class β¦ -
django-celery RuntimeError: Model class apps.scrawler.models.Url doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
my django(1.11) project layout is like below: βββ apps β βββ accounts β βββ reports β βββ scrawler β βββ settings.py βββ config β βββ settings β βββ celery.py βββ cron_system β βββ ping β βββ jobs.py and apps/seetings.py is following snippet: LOCAL_APPS = [ 'apps.accounts.apps.AccountsConfig', 'apps.scrawler.apps.ScrawlerConfig', 'apps.reports.apps.ReportsConfig', ] and in the config/settings/base.py I imported them as below: from apps import settings as app_settings INSTALLED_APPS += apps_settings.LOCAL_APPS django itself detects the apps and models. but celery doesn't. in the cron_system/ping/jobs.py i imported one of apps.scrawler models, but when the celery worker starts, it raises an error: RuntimeError: Model class apps.scrawler.models.Url doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. this error is raised for all the models in all models of apps. if i import a model from apps.scrawler.models or from apps.accounts.models this error will be shown. -
LinkedIn Oauth2.0 Django login using Python-social-auth, invalid redirect URI
I'm trying to add "Login via LinkedIn" functionality in my website. My Django project name is "botdjango" and app name is "botgetdata". These are the steps I followed- pip install social-auth-app-django Made these changes in "settings.py" INSTALLED_APPS = [ 'botgetdata', 'social_django', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware',] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social.apps.django_app.context_processors.backends', 'social.apps.django_app.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social.backends.linkedin.LinkedinOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = 'my_key' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET ='my_secret' Made migrations using- python manage.py migrate This is my "urls.py" - from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('botgetdata.urls')), url(r'^login/$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), url(r'^oauth/', include('social_django.urls', namespace='social')), ] LOGIN_URL = 'login' LOGOUT_URL = 'logout' LOGIN_REDIRECT_URL = '/home' This the code for login button on webpage: <a href="{% url 'social:begin' 'linkedin-oauth2' %}">Login with LinkedIn</a><br> I'm attaching the screenshots of login page and then the error I'm getting.Login Page. Error. These are the callback/redirect URL's I have tried on LinkedIn- http://127.0.0.1:8000/complete/linkedin-oauth2/ http://127.0.0.1:8000/sociall-auth/complete/linkedin-oauth2/ http://localhost:8000/login/linkedin-oauth2/ http://127.0.0.1:8000/login/linkedin-oauth2/ I have gone through many questions already posted here on β¦ -
uploading image using ImageField in Django
I am trying to upload files using Django's ImageField and forms everytime I click submit on the form. The form.is_valid returns false So I printed forms.errors It says photo2 This field is required. photo1 This field is required. I select the image files I want to upload and it still says field is required. Here is view of my settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Here is views.py def upload(request): if request.method=="POST": prod = Product() form = UploadForm(request.POST, request.FILES) if form.is_valid(): prod.name = form.cleaned_data.get('name') prod.brand = form.cleaned_data.get('brand') prod.material = form.cleaned_data.get('material') prod.color = form.cleaned_data.get('color') prod.price = form.cleaned_data.get('price') prod.discount = form.cleaned_data.get('discount') prod.sex=form.cleaned_data.get('sex') prod.photo1 = form.cleaned_data('photo1') prod.photo2 = form.cleaned_data('photo2') prod.save() return render(request, 'upload.html', {'form': form}) else: x = form.errors return render(request,'upload.html', {'alert':x}, {'form': form}) else: form = UploadForm return render(request, 'upload.html', {'form': form}) Here is my models.py class Product(models.Model): name = models.CharField(max_length=200, default='N/A') brand = models.CharField(max_length=50, default='N/A') material = models.CharField(max_length=50, default='N/A') color = models.CharField(max_length=20, default='N/A') price = models.IntegerField(default=0) discount = models.IntegerField(default=0) discountprice = models.IntegerField(default=0) photo1 = models.ImageField(upload_to='productphotos/') photo2 = models.ImageField(upload_to='productphotos/') Male = 'M' Female = 'F' Both = 'Both' Genders = ((Male, 'Male'),(Female, 'Female'), (Both, 'Both')) sex = models.CharField(choices=Genders, default=Male, max_length=6) Thank you for help in advance. I can upload forms.py β¦ -
Django signals is sending 2 times
Hi guys I'm trying to use Django signals in my application but the post_save is sending 2 times, and the post_delete is sending 1 like is supposed to do. my signals.py @receiver([pre_save,post_delete], sender=Researcher) def print_request(sender, **kwargs): print('Request finished!') result in my terminal when I save an object Request finished! Request finished! thanks -
Is it possible to call from class (Tesserocr) to def (Google Cloud) and from def to HTML, using Django and in Python 3?
I am trying to call the class Tesserocr to def Google Cloud Translate API and to call Google Translate API to HTML file, using Python 3.6 and Django 2.0.6. But it gave a lot of errors. Firstly I will show the original codes. Then I will explain small modified codes. In the enf, you can check the whole modified source of 3 files (views.py, ocr_form and ocr_form.js) via Gist link. 1. Original codes: Tesseorcr: from django.http import Http404 from django.http import HttpResponse from django.http.response import JsonResponse from django.shortcuts import get_object_or_404, render from django.views.decorators.csrf import csrf_exempt from django.views.generic.base import View, TemplateView from google.cloud import translate from PIL import Image, ImageFilter from tesserocr import PyTessBaseAPI class OcrFormView(TemplateView): template_name = 'documents/ocr_form.html' ocr_form_view = OcrFormView.as_view() class OcrView(View): def post(self, request, *args, **kwargs): with PyTessBaseAPI() as api: with Image.open(request.FILES['image']) as image: image = image.convert('RGB') sharpened_image = image.filter(ImageFilter.SHARPEN) api.SetImage(sharpened_image) utf8_text = api.GetUTF8Text() return JsonResponse({'utf8_text': utf8_text}) ocr_view = csrf_exempt(OcrView.as_view()) Google Translate API: # Instanciando o cliente translate_client = translate.Client() # translate_client = translate.Client.from_service_account_json('meu_projecto.json') # O texto para traduzir The text to translate text2 = text # O idioma-alvo target = 'pt' # Translates some text into Russian translation = translate_client.translate( text2, target_language=target) print(u'Texto: {}'.format(text2)) print(u'TraduΓ§Γ£o: {}'.format(translation['translatedText'])) 2. β¦ -
ImportError: No module named django.core.exceptions in google app engine
djangoforms.py module was missing from google.appengine.ext.db. So I manually putted the module there from net. But it can't import django.core.exceptions. I've two version of python installed in my windows 10 and have added python 2.7 on the path. IDLE 2.7 successfully runs "import django . Below is the log console message of google app engine. Have googled numerous times but couldn't find any fruitful solution. Any help?[I'm a newbie who is learning from head first python(1st edition)] ERROR 2018-06-18 09:47:26,513 cgi.py:122] Traceback (most recent call last): File "F:\Coding Practise\head_first_series\python\ch10_tariq\hfwwgapp\hfwwg.py", line 5, in from google.appengine.ext.db import djangoforms File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\db\djangoforms.py", line 98, in import django.core.exceptions ImportError: No module named django.core.exceptions -
Accessing request data object
I am sending the following post Data to django Rest API Request URL: http://localhost:8000/polls/ Request Method: POST Status Code: 200 OK Remote Address: 127.0.0.1:8000 Referrer Policy: no-referrer-when-downgrade Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://localhost:8100 Content-Length: 90 Content-Type: text/html; charset=utf-8 Date: Mon, 18 Jun 2018 11:01:54 GMT Server: WSGIServer/0.2 CPython/3.6.5 Vary: Origin X-Frame-Options: SAMEORIGIN Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Connection: keep-alive Content-Length: 83 content-type: text/plain Host: localhost:8000 Origin: http://localhost:8100 Referer: http://localhost:8100/ User-Agent: Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.170 Mobile Safari/537.36 0: {id: "1", username: "admin", password: "admin", user_group_id: "1", status: "1"} The sent here will first be authenticated against the one saved in the database. I am trying to access this data but failing to do so . When I process the data using json parse case 1. def dunction(request) data = json.loads(request.body.decode("utf-8")) vak=data return HttpResponse(vak) Then the following response is received {'id': '1', 'username': 'admin', 'password': 'admin', 'user_group_id': '1', 'status': '1'} case 2. When manipulating the same code data = json.loads(request.body.decode("utf-8")) vak=data[0] return HttpResponse(vak) received response idusernamepassworduser_group_idstatus Case 3. def dunction(request): data = json.loads(request.body.decode("utf-8")) vak=data.username return HttpResponse(vak) throws error 'list' object has no attribute 'username' FYI, Here I am trying to create a β¦ -
Correct/better implementation for the model of a 'Like' in Django
I am currently working on a project that requires the implementation of a typical 'like' button on posts (submitted by users). Which one of the following two implementation would be a better choice considering every aspect - performance, integrity, etc ? class Post(models.Model): . . likes = models.ManyToManyField(User, blank = True) . . or, class Like(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) #considering we have a Post model without the above ManyToMany relation post = models.ForeignKey(Post, on_delete = models.CASCADE) . . -
Backend deletion inisde the array
I am wondering what is the best way to PATCH an array of things/ objects. Let's assume I have records array inside my model and I want to add some records to it using my frontend application. I'm sending just those in the request as: records: [{ name: 'record_1' }, { name: 'record_2' }] What if I now want to delete record_2? Should my approach be: Send records: [{ name: 'record_1' }] as a whole, so the backend knows that we deleted the record_2 Send the array with some flag like deleted: true so it looks like this: records: [{ name: 'record_1' }, { name: 'record_2', deleted: true }] Frontend wise it is easier to do the first one, but how about the backend?