Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django pass model to widget in ModelForm
I have a ModelForm that has an extra field that is a custom widget. I can add an extra field with a widget and pass arbitrary key values to it when constructing the widget. I'm also able to access model data within the ModelForm in the __init__ function. My problem lies in that adding an extra field in the ModelForm requires doing so outside the __init__ function while accessing model data is only possible from within the __init__ function. class SomeForm(forms.ModelForm): title = None def __init__(self, *args, **kwargs): some_data = kwargs['instance'].some_data # ^ Here I can access model data. super(SomeForm, self).__init__(*args, **kwargs) self.fields['some_extra_field'] = forms.CharField(widget= SomWidget()) # ^ This is where I would pass model data, but this does not add the field. class Meta: model = Page fields = "__all__" some_extra_field = forms.CharField(widget= SomeWidget()) # ^ I can add a field here, but there's no way to pass some_data to it. I've also tried setting self.some_data in __init__, but it's still not accessible when I try to use self.some_data when setting some_extra_field at then end of the class. How should pass model data to a widget in a ModelForm? -
How to pass values from one subquery to another queryset?
could you support me with the following question? I have this models: class Tarifa(models.Model): limite_i = models.DecimalField(max_digits=10, decimal_places=2) limite_s = models.DecimalField(max_digits=10, decimal_places=2) class Calculator(models.Model): tarifa = models.ForeignKey(Tarifa, on_delete=models.CASCADE) base = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) limite = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) I have a first queryset that brings the information of a row of my calculator model: qsl1 = Calculator.objects.values_list('base') This queryset returns all the amounts that I have in base: <QuerySet [(Decimal('3000.00'),), (Decimal('5000.00'),), (Decimal('1000.00'),)]> Later, I enter this query as a subquery in the following queryset: qsl2 = Tarifa.objects.filter( Q(limite_s__gte=qsl1) & Q(limite_i_isr__lte=qsl1)) .values_list('limite_i') This second query values that my 'limit_s'> = 'base' and 'limit_i' <= 'base' and then bring me the value of 'limit_i' Now the problem is that I only return the comparison of the first value that is 3000.00, I also need to make the comparison of 5000.00 and 1000.00 and all the other values that are added. But I do not know how you could support me, thank you very much. -
How to query strings numerically in Django
I'm using Django to query a legacy Postgres 10 database via form entry. When a user enters their age I'm querying the variable against two columns related to age (minimum age, maximum age). These columns are set as Character Fields and always contain data in the form of "40 Years", "20 Weeks" etc. How would I go about querying these columns numerically i.e. minimum age > X and maximum age < X? I've tried using regex to isolate the numerical portion of the string then comparing the integer against another variable but get a syntax error: Test_Query = Eligibilities.objects.filter(Q((minimum_age__regex=r'^\d+')__gte = AgeFormData), Q((minimum_age__regex=r'^\d+')__lte = AgeFormData)) I've also tried splitting the string and casting it as an integer with no luck either. If a user enters their age as 40 Years I'd expect all records where minimum age is greater or equal to 40 and maximum age is less or equal to 40 to appear. Thanks for any help! -
LANGUAGE_CODE set to es-mx but labels for forms in english
Is there a way to set all labels, apart from error messages, to other languages like spanish. I can set error messages with: LANGUAGE_CODE = 'es-mx' But form labels are in english: settings.py import os from decouple import config # SITE_ROOT = root() # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = ['127.0.0.1', 'stickers-gallito-app.herokuapp.com', 'stickersgallito.pe', 'www.stickersgallito.pe'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shop', 'search_app', 'cart', 'stripe', 'order', 'crispy_forms', 'embed_video', 'storages', 'marketing', 'django.contrib.humanize', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'stickers_gallito.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'shop', 'templates/'), os.path.join(BASE_DIR, 'search_app', 'templates/'), os.path.join(BASE_DIR, 'cart', 'templates/'), os.path.join(BASE_DIR, 'order', 'templates/'), ] , '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', 'shop.context_processor.menu_links', 'shop.context_processor.has_shop', # 'cart.context_processor.current_time', 'cart.context_processor.cart_items_counter' ], }, }, ] WSGI_APPLICATION = 'stickers_gallito.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # SECURITY WARNING: don't run with debug turned on in production! if DEBUG: # Redirecciona www y http a https SECURE_SSL_REDIRECT … -
'User' object is not iterable at Django 1.11
I have a view with two forms, one creates an object, the second updates (for the user). The first works, the second gives an error. @method_decorator(login_required, name='dispatch') class ProfileEditCompetencies(TemplateView): template_name = 'accounts/user_edit_competencies.html' create_form_class = ProfileCreateCompetenciesForm update_form_class = ProfileEditCompetenciesForm def post(self, request): create_form = self.create_form_class(request.POST or None, prefix='create') update_form = self.update_form_class(request.POST or None, prefix='update') context = self.get_context_data(create_form=create_form, update_form=update_form) if create_form.is_valid(): create_form.save() return redirect(self.request.path) if update_form.is_valid(): obj = update_form.save(commit=False) obj.user = request.user #Error obj.save() return redirect(self.request.path) return self.render_to_response(context) def get(self, request, *args, **kwargs): return self.post(request, *args, **kwargs) -
add ajax button in django to update user`s choice
I have followed the tutorial by Mozilla described here and have made some modifications to make it into a movie library. I would like to add the option for a user when he opens a movie to be able to mark it as "seen". I would like to do that using ajax so the button the user would click would change as well without refreshing the page. This is the model used to store the user choice class Seenit(models.Model): username = models.CharField(max_length=150) movieid = models.ForeignKey('Movie', on_delete=models.CASCADE) haveyouseenit = models.BooleanField(default=False, null=True, blank=True) def __str__(self): return f"{self.username}|{self.movieid.id}" this is from the urls.py re_path(r'^add_to_seen/(?P<pk>.*)', views.Addseen.as_view(), name='add_to_seen') This is from the views.py class Addseen(generic.DetailView): model = Seenit def get(self, request, *args, **kwargs): if request.is_ajax(): check = get_object_or_404(Seenit, movieid=id, username=request.user.get_username()) if not check.haveyouseenit: check.haveyouseenit == True check.save() return HttpResponse("1") else: check.haveyouseenit == False check.save() return HttpResponse("0") and this is from the movie_details.html showing the button along with an attempt I made for the ajax button. <div id="seen"> {% if user.is_authenticated %} <button class="add_button" id="seen">Have seen</button> <b style="color: #3b97f4" id="message"></b> {% if seen %} <script> $("#seen").css({"background-color": "#f4b6e0", "color": "white"}); </script> {% endif %} {% endif %} <script> $(document).ready(function () { $("#seen").click(function () { $.get("/add_to_seen/{{ movie.id }}", … -
I'm trying to delete a row using an array. Can you tell me the grammar of orm?
I'm trying to delete a row using an array. Can you tell me the grammar of orm? def todo_delete_ajax(request): todo_ids = request.POST.getlist('todo_arr[]') # result : todo_ids : ['76', 97] if todo_ids: print("todo_ids : ", todo_ids) return redirect('/todo/') else: print("todo_ids : ", todo_ids) return redirect('/todo/') I want to use Django orm and delete 76,97 of todo model Thank you if you let me know how. -
skipping the complete row if len() of column is lower than 10 in python
I'm trying to apply an if statement in my django view script that would skip the complete row of the product if the description lenght is less than 10, but I don't know how to achieve this.. This is my Django view that calls an API and save the data into my database and as you will see in the commented section this is what I came out with so far: def api_data(request): if request.GET.get('mybtn'): # to improve, == 'something': resp_1 = requests.get( "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD", headers={ "Headout-Auth": HEADOUT_PRODUCTION_API_KEY }) resp_1_data = resp_1.json() base_url_2 = "https://www.headout.com/api/public/v1/product/get/" translator = Translator() for item in resp_1_data['items']: print('parsing, translating and saving item {}'.format(item['id'])) # concat ID to the URL string url = '{}{}'.format(base_url_2, item['id'] + '?language=fr') # make the HTTP request resp_2 = requests.get( url, headers={ "Headout-Auth": HEADOUT_PRODUCTION_API_KEY }) resp_2_data = resp_2.json() descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...' #what I tried so far #if len(descriptiontxt) < 10: # skip the complete row and go to the next one soup = BeautifulSoup(descriptiontxt, 'lxml') parsed = soup.find('p').text translation = translator.translate(parsed, dest='fr') titlename = item['name'] titlefr = translator.translate(titlename, dest='fr') destinationname = item['city']['name'] destinationfr = translator.translate(destinationname, dest='fr') Product.objects.get_or_create( title=titlefr.text, destination=destinationfr.text, description=translation.text, link=item['canonicalUrl'], image=item['image']['url'] ) time.sleep(2) return render(request, "C-cret-form.html") Please help. -
How to save the value of a range slider (multiple input) in Django
I have a range slider as a one file of my form. I can update the value of the item with js. Sending the checkboxes state works, however, for some reason I cannot get range slider value. Here's my template: <form method="POST"> {% csrf_token %} <table id="levels"> <label class="container">Easy <input type="checkbox" name="checks" value="1"> <span class="checkmark"></span></label> <!--you get the idea--> </table> <input type="range" min="1" max="120" value="120" class="form-control-range" id="time_slider"> <b> <span id="slider_value" ></span></b> min. <input type="submit" id="update" name = "update" value="Filter"> </form> <script> var slider = document.getElementById("time_slider"); var output = document.getElementById("slider_value"); output.innerHTML = slider.value; slider.oninput = function() { output.innerHTML = this.value; } </script> and my view.py: def item_list(request): items = Items.objects.all() if request.POST: if 'update' in request.POST: check_list = request.POST.getlist('checks') time = request.POST.get('slider_value') if check_list: items=items.filter(level__in=check_list) if time: items=items.filter(time__lte=time) If I print the check_list there are all the checkboxes I tick. The slider is responsive, script works but no value is send to my view. All I get is "None". Switching get to time_slider is not helping either. What I did wrong? -
Storing sensitive data in Django
I'm building a project where i will be able to save an API key, then this key will be used to perform some operations on my site. Obviously, no one should access the key, except my code that will perform some tasks using those keys. At the actual moment, the keys are stored on my database and they are not encrypted, but now i would like to make this system as safe as possible, so that even if someone has access to my credentials, he can't use it. The problem is that i know very little about security and encription. My first thought was to encrypt the keys, but i don't really know how to do that. Basically, that's how it should work: the keys are submitted using a form -> the keys must be encrypted and saved on my db -> later on, when i need to perform a task, those keys should be decrypted in order to do what i need Is my approach correct? And how can i accomplish that in Django? Here is my current view: def homepage(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form … -
Django models: How to set up field value based on another field when new model item created in admin interface?
I have two related models: Plaint and WritOfExecutionTemplate. It is possible to add new template on plaint edit page using admin.TabularInline class. When user create new template from plaint page, I need to fill 2 power of attorney (POA) fields based on current plaint. User allowed to change POAs before template will be saved. I tried to set callback method to fieldsdefault` attribute, but I have problem getting referenced plaint object. class AbstractGeneratedCaseDocument(AbstractBaseModel): class Meta: abstract = True case = models.ForeignKey( verbose_name=_('case'), to='Case', on_delete=models.PROTECT, ) power_of_attorney = models.ForeignKey( verbose_name=_('power of attorney'), to='ImportedDocument', on_delete=models.PROTECT, null=True, blank=True, related_name='+', ) power_of_attorney_2 = models.ForeignKey( verbose_name=_('power of attorney') + ' 2', to='ImportedDocument', on_delete=models.PROTECT, null=True, blank=True, related_name='+', ) class Plaint(AbstractGeneratedCaseDocument): pass class WritOfExecutionTemplate(AbstractBaseModel, WhoDidItMixin): plaint = models.ForeignKey( to='Plaint', verbose_name=_('plaint'), on_delete=models.PROTECT ) def get_poa1_from_plaint(self): if (self.plaint.power_of_attorney is not None and self.plaint.case.plaintiff_representative == self.plaint.power_of_attorney.relative_person): poa = self.plaint.power_of_attorney else: poa = None return poa def get_poa2_from_plaint(self): # The same as for the first power of attorney if (self.plaint.power_of_attorney_2 is not None and self.plaint.case.plaintiff_representative == self.plaint.power_of_attorney_2.relative_person): poa = self.plaint.power_of_attorney_2 else: poa = None return poa power_of_attorney = models.ForeignKey( verbose_name=_('power of attorney'), to='ImportedDocument', on_delete=models.PROTECT, #null=True, #blank=True, related_name='+', default=get_poa1_from_plaint, ) power_of_attorney_2 = models.ForeignKey( verbose_name=_('power of attorney') + ' 2', to='ImportedDocument', on_delete=models.PROTECT, null=True, … -
How to get ForeignKey field value during new model creation?
I'm looking for the most efficient way to implement this kind of mechanism in Django model. Let's assume a situation, where there are 2 very simple models: class FKModel(models.Model): value = BooleanField() class AModel(models.Model): fk = models.ForeignKey(FKModel) a_value = models.CharField(max_length=150) def clean(self, *args, **kwargs): # the line below is incorrect if not self.fk.value: # <--- how to do this in a proper way? raise ValidationError('FKModel value is False') super(AModel, self).clean(*args, **kwargs) def save(self, *args, **kwargs): self.full_clean() super(AModel, self).save(*args, **kwargs) I know, that I can do somethink like FKModel.objects.all()/.get(), but I don't think it is the best solution (as it requires additional requests to database). -
I want to know why an error occurred when I sent an array to view with jquery ajax
hello I have a question I am trying to implement row delete with jquery ajax. I sent an array to view in jquery ajax error has occured. The contents of the error are as follows. error message: During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\django_inflearn2\todo\views.py", line 23, in todo_delete_ajax todo_ids = request.POST['todo_arr'] File "C:\django_inflearn2\venv\lib\site-packages\django\utils\datastructures.py", line 80, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'todo_arr' [02/Jun/2019 06:11:29] "POST /todo/todo_delete_ajax/ HTTP/1.1" 500 19607 if you know what is the resont and how fix plase let me know thanks~! jquery , ajax $('#todo_delete_button').click(function(e){ e.preventDefault(); // todo_check alert("삭제 버튼 ") // Get checked checkboxes var todo_arr = []; $('.td_check').each(function() { if (jQuery(this).is(":checked")) { var id = this.id; todo_arr.push(id); } }); alert('todo_arr : '+ todo_arr) $.ajax({ type: "POST", url: 'todo_delete_ajax/', data: { todo_arr:todo_arr, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(result) { alert('todo_delete_ajax is success '); } }); }) and url pattern path('todo_delete_ajax/',views.todo_delete_ajax, name ="todo_delete_ajax"), view def todo_delete_ajax(request): # print("request " , request ) todo_ids = request.POST['todo_arr'] print("todo_ids : ", … -
problems when saving a file in database
I want that when I save a file from the disk to the database I do not overname it, only that I overwrite it or just save the url without copying it with another name. -
Pop-ups in Django-TinyMCE using Amazon S3 are blank
Pop-ups in Django-TinyMCE such as creating a table, inserting images and viewing HTML are coming up blank when using Amazon S3 to store my static files. All other TinyMCE features are working properly. It throws the following errors in the Chrome console: tiny_mce_popup.js:5 Uncaught DOMException: Blocked a frame with origin "https://<my-bucket>.s3.amazonaws.com" from accessing a cross-origin frame. at Object.init (https://<my-bucket>.s3.amazonaws.com/static1/assets/js/tiny_mce/tiny_mce_popup.js:5:107) at https://<my-bucket>.s3.amazonaws.com/static1/assets/js/tiny_mce/tiny_mce_popup.js:5:4764 init @ tiny_mce_popup.js:5 (anonymous) @ tiny_mce_popup.js:5 tiny_mce_popup.js:5 Uncaught TypeError: Cannot read property 'plugin_url' of undefined at Object.getWindowArg (tiny_mce_popup.js:5) at Object.requireLangPack (tiny_mce_popup.js:5) at source_editor.js:1 I have set the following variables, but the same error persists In settings.py TINYMCE_JS_URL = '%stiny_mce/tiny_mce.js' % MEDIA_URL In tiny_mce_pop.js, tiny_mce.js and init_tinymce.js document.domain = 'mysite.org'; In the head of base.html <script type="text/javascript">document.domain = 'mysite';</script> Any help would be appreciated. Thanks! -
NoReverseMatch at /sitemap.xml Django Python
Django Noob here. NoReverseMatch at /sitemap.xml Reverse for 'article_detail' not found. 'article_detail' is not a valid view function or pattern name. See models.py screenshot (code) to understand the error. I don't know what I should put in place of article_details (see the code for explanation). Your help will appreciable. Error- Project Structure- Code- Dipesh_Pal Module Code- settings.py- INSTALLED_APPS = [ 'django.contrib.sitemaps', 'django.contrib.sites', ] SITE_ID = 1 urls.py- home Module Code- sitemaps.py- urls.py- models.py- The error in line 37. I am not exactly sure what I should put in place of "article_detail" or I am not sure what exactly wrong in my code. For your information, I am referring this YouTube video- Click Here My Github Repo for this App- Click Here -
If statement to fix list index out of range error - Python
I'm setting up a Django views that calls an API and save the data into my database but I keep getting a listindex out of range error everytime the loop hit the last item in the response. This is what the Traceback looks like: Internal Server Error: /form/ Traceback (most recent call last): File "C:\Users\locq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Users\locq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\locq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\locq\Desktop\Coding\UVERGO_SEARCH\venv\src\search\views.py", line 126, in api_data descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...' IndexError: list index out of range As we can see above, the error is pointing toward line 126: descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...' So I'm trying to fix this by adding an If statement to the line in the following Django view: def api_data(request): if request.GET.get('mybtn'): # to improve, == 'something': resp_1 = requests.get( "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD", headers={ "Headout-Auth": HEADOUT_PRODUCTION_API_KEY }) resp_1_data = resp_1.json() base_url_2 = "https://www.headout.com/api/public/v1/product/get/" translator = Translator() for item in resp_1_data['items']: print('parsing, translating and saving item {}'.format(item['id'])) # concat ID to the URL string url = '{}{}'.format(base_url_2, item['id'] + '?language=fr') # make the HTTP request resp_2 = requests.get( url, headers={ "Headout-Auth": HEADOUT_PRODUCTION_API_KEY }) … -
Django Testing: Test a form with required ChoiceField
I have a form with a ChoiceField and in my test, it fails with the error: {'questions': ['This field is required.']} The Form: class QuestionForm(forms.Form): questions = forms.ChoiceField( label="Select the question", ) The Test class TestQuestionForm(TestCase): def setUp(self): self.conference = ConferenceFactory() def test_form(self): form = QuestionForm( data={}, initial=None, prefix=None, questions=self.conference.get_question_choices(), ) assert form.is_valid() Why is form.is_valid() failing due to the required field? -
Rest Framework Seralizer Always returns false from is_valid
I am setting up a database of cars inventory and trying to filling it up with json data provided by an api. What is wrong with my seralizer? This is a windows , Django2 and Sqlite database Python3 seralizer.py ''' from rest_framework import serializers from .models import SavedInventory class EmbedSerializer(serializers.ModelSerializer): class Meta: model = SavedInventory fields = 'all' ''' views.py ''' vin = form.cleaned_data['vin'] links={"X-RapidAPI-Host":settings.VINDECODERHOST, "X-RapidAPI-Key": settings.VINDECODERKEY} r = requests.get("https://vindecoder.p.rapidapi.com/decode_vin?vin="+ vin + "&key=" + settings.VINDECODERKEY) json = r.json() serializer = EmbedSerializer(data=json) if serializer.is_valid(): saved = serializer.save() return render(request, 'saved.html', {'embed': embed}) else: return HttpResponse('ERROR Seralizer') ''' This gives me ERROR Seralizer as output and no change in the database -
IndexError at /form/ - list index out of range in Django
I'm setting up a Django views that calls an API and save the data into my database but I keep getting a listindex out of range error everytime the loop hit the last item in the response. This is what the Traceback looks like: Internal Server Error: /form/ Traceback (most recent call last): File "C:\Users\locq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Users\locq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\locq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\locq\Desktop\Coding\UVERGO_SEARCH\venv\src\search\views.py", line 126, in api_data descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...' IndexError: list index out of range As we can see above, the error is pointing toward line 126: descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...' And this is my Django View function: def api_data(request): if request.GET.get('mybtn'): # to improve, == 'something': resp_1 = requests.get( "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD", headers={ "Headout-Auth": HEADOUT_PRODUCTION_API_KEY }) resp_1_data = resp_1.json() base_url_2 = "https://www.headout.com/api/public/v1/product/get/" translator = Translator() for item in resp_1_data['items']: print('parsing, translating and saving item {}'.format(item['id'])) # concat ID to the URL string url = '{}{}'.format(base_url_2, item['id'] + '?language=fr') # make the HTTP request resp_2 = requests.get( url, headers={ "Headout-Auth": HEADOUT_PRODUCTION_API_KEY }) resp_2_data = resp_2.json() descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...' #Parse soup = … -
How to fix "No result set to fetch from"
I am trying to run some sql queries on a db to use the results but I keep getting the 'No result set to fetch from'. Where could the problem be? When running the code I am directed to the following line; mycursor=mydb.cursor() mycursor.execute=("""SELECT SUM(games) games FROM (SELECT Count(*) games FROM `results` WHERE HTgoals>ATgoals AND Home_team='{0}' UNION SELECT COUNT(*) games FROM `results` WHERE ATgoals>HTgoals AND Away_team='{0}') T""" .format(home_team)) _Home_team_Total_wins= mycursor.fetchall() #Home team total wins_ -
comment system switching to ajax, so not going to a different page
I was able to write comment system in python, django. but to make a comment the user has to move to different url. I don't want the users to move to a different page to write,edit,delete comment. I googled and it seems like I have to use ajax but I'm not sure. can someone guide me how to do it? views.py @login_required def comment_new(request, post_pk): post = get_object_or_404(Post, pk=post_pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = request.user comment.save() return redirect('home') else: form = CommentForm() return render(request, 'community/comment_form.html', { 'form':form, }) @login_required def comment_edit(request, post_pk, pk): #post = get_object_or_404(Post, pk=post_pk) comment = get_object_or_404(Comment, pk=pk) if comment.author != request.user: return redirect(comment.post) if request.method == 'POST': form = CommentForm(request.POST, instance=comment) if form.is_valid(): comment = form.save() return redirect(comment.post) else: form = CommentForm(instance=comment) return render(request, 'community/comment_form.html', { 'form':form, }) @login_required def comment_delete(request, post_pk, pk): comment = get_object_or_404(Comment, pk=pk) if comment.author != request.user: return redirect(comment.post) if request.method == 'POST': comment.delete() return redirect(comment.post) return render(request, 'community/comment_confirm_delete.html', { 'comment':comment, }) models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-id'] def get_edit_url(self): return … -
How to fix error "ValueError: <Follower: Follower object (None)> instance is not saved." Use bulk = False or save the object first. "
I wanted to create a follower system, and I get a "ValueError: instance is not saved." Use bulk = False or save the object first. " .Please how to solve this problem, sorry for my bad writing!! #my models.py from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Follower(models.Model): follower = models.ForeignKey(User, related_name='following', on_delete=None) following = models.ForeignKey(User, related_name='followers', on_delete=None) class Meta: unique_together = ('follower', 'following') def __unicode__(self): return u'%s follows %s' % (self.follower, self.following) #in the interpreter >>> from followers.models import * >>> john = User.objects.create_user('john', 'lennon@thebeatles.com', 'password') >>> paul = User.objects.create_user('paul', 'mccartney@thebeatles.com', 'password') >>> george = User.objects.create_user('george', 'harrison@thebeatles.com', 'password') >>> ringo = User.objects.create_user('ringo', 'starr@thebeatles.com', 'password') #the mistake comes from here >>> john.following.add(Follower(following=paul)) and I get in add "the object first." % obj ValueError: instance isn't saved. Use bulk=False or save the object first.` -
Adding a time.sleep() method for Google Translate API in python
I'm setting up a Django Views that requests products data from an API, parse them with BeautifulSoup, apply the googletrans module and save the response into my Postgresql database. I have a 429 HTTP error when I run my script because I send to many requests at once and I was adviced to add a time.sleep() method of 2 seconds to fix the issue. The only thing is that I'm not sure where should I place this method in my script, and I need to make sure that its the right way to do it before risking of getting my IP address blocked by Google tranlsate API again. This is my Views: from bs4 import BeautifulSoup from googletrans import Translator import requests import json def api_data(request): if request.GET.get('mybtn'): # to improve, == 'something': resp_1 = requests.get( "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD", headers={ "Headout-Auth": HEADOUT_PRODUCTION_API_KEY }) resp_1_data = resp_1.json() base_url_2 = "https://www.headout.com/api/public/v1/product/get/" translator = Translator() for item in resp_1_data['items']: print('translating item {}'.format(item['id'])) # concat ID to the URL string url = '{}{}'.format(base_url_2, item['id'] + '?language=fr') # make the HTTP request resp_2 = requests.get( url, headers={ "Headout-Auth": HEADOUT_PRODUCTION_API_KEY }) resp_2_data = resp_2.json() descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...' #Parsing work soup = BeautifulSoup(descriptiontxt, 'lxml') parsed = … -
how to import the "django-sse" module?
I want to import the module Django-SSE in one of my projects, but it errors because it has subtraction sign. I've tried to import the library like this import django-sse and import django_sse but none of theme worked. so i'll be appreciate if you help me to import it and tell me is there any documentation about it?