Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Filter - update results without refreshing
I'm using Django-filter to filter and sort my listview queryset. Current stats - when user submit filters, the page refreshes with the new query. My goal - get the list update without having to refresh the page + have the list update on each filter selection (rather than waiting for user to select all desired filters and submit) I believe the solution will include Ajax, however I'm not sure how to get into it with Django filter and unfortunately there's no mention whatsoever in docs. Filter.py class FestivalFilter(django_filters.FilterSet): style = django_filters.MultipleChoiceFilter(choices=Festival.style_choices,widget=forms.CheckboxSelectMultiple,) camp_style = django_filters.MultipleChoiceFilter(choices=Festival.camp_style_choices,widget=forms.CheckboxSelectMultiple,) friendly = django_filters.BooleanFilter(method='avg_above3',) ..... def avg_above3(self, queryset, name, value): return queryset.annotate(avg=Avg('Festival_Reviews__{}'.format(name))).filter(avg__gt=3) views.py from django.views.generic import (TemplateView, ListView) from festival_list import models from django.views import generic from .filter import FestivalFilter from .filter_mixin import ListFilteredMixin from el_pagination.views import AjaxListView from django.contrib.auth.mixins import (LoginRequiredMixin, PermissionRequiredMixin, UserPassesTestMixin) from braces.views import SelectRelatedMixin from django.views.decorators.http import require_GET from django.urls import (reverse, reverse_lazy) from django.shortcuts import render class HomePage(ListFilteredMixin, AjaxListView): template_name = 'index.html' page_template = 'index_page.html' model = models.Festival paginate_by = 12 context_object_name = 'festivals' filter_set = FestivalFilter AjaxListView used for pagination and not related to the filtering task. template filter menu: <form action="" method="get" id="filter-form"> <div class="row filters-row text-center"> {% for style … -
Preventing more than X instances of a model from being created
I want to create some sort of validation that prevents more than 3 instance of a certain model from being created that meet a certain set of criteria. 1) These model instances are ONLY created in /admin (i.e there is no view that creates these models, thus, I can't do the validation in a view 2) My understanding is that def clean() within forms.py only applies to font facing forms that you'd see on a webpage. As these model instances are only created in the backend, again, I don't think that I can create a form and use def clean() to perform this validation 3) I considered creating a validator in my models.py to do this validation, but I'm not sure how to get the instance of the model within a validator. My understanding is that validators can only be used to validate data at a field level. This leaves me with some confusion. I'm not sure where I can perform my validation to ensure that only 3 instances of a model with X criteria is ever created. Thanks for your help! -
There is a template error with Model instances
I am creating a blog with system of comments and tags. Now I faced to a template problem with Model instances. First I put status to all new Posts as "draft" but now I set a the status to 'published' and I got this error message. If you need more code olease tell me. I tried to watch the behavior of my code when I was adding new elemets to the my code. models.py class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='published') class Post(models.Model): STATUS_CHOICE = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=250) slug = models.CharField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now()) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICE, default='published') class Meta: ordering = ('-publish',) def __str__(self): return self.title objects = models.Manager() published = PublishedManager() tags = TaggableManager() def get_absolute_url(self): return reverse('blog_site:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) views.py def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) # List of active comment fot this post comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object bot don't save to database yet … -
Overriden Django authentication is not returning user object
I have overridden default Authentication system of Django.But this is not returning the user object. from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission class ModelBackend(object): """ Authenticates against settings.AUTH_USER_MODEL. """ def authenticate(self, username=None, password=None, **kwargs): UserModel = get_user_model() if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: user = UserModel._default_manager.get_by_natural_key(username) print("Database pass : ",user.password,"incoming pass : ",password) # if user.check_password(password): # print(user.check_password(password)) # return user if str(user.password) == str(password): print(12345,user) return user except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a non-existing user (#20760). UserModel().set_password(password) It's always showing incorrect password although passwords are same and It's printing out 12345 and user also but it is not returning user. -
Raise MultiValueDictKeyError by request.FILES to get base64 image data
Actually i need to get base64 image data generated by croppie javascript library. The image data look like below. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAgAElEQVR4Xs1dB5xU1dX/39em7c422GXpVZGmWACxImAviYnYY/1UjLF8iYkxxq4xlk+jscZek1iiiUajRiMWehEFAemwLGyfnfravd/v3Dd39zEsxpYyuO7szKv3f8r/nHvueQz/5a9NmzbFMu32KF/ju4JrIwX8XbkQ9WCoFEKU+55fLsBrOBcQnLX6QksLwdOciw7XE43cxwqmsRWciRUJs2bF5MkD8v/Nt8z+2y5uwYIt8Wg0ewDApmoMU4XAHgA0IQQAAfrlc3qvXgK+z8E5hy8EPMEgePCZ4LQHAxcCgtFvxoXgSwDxtg/xNi/zPzxm771z/01j8B8HRAhhLFmyZoLvO1M5F9MMQ5ukaZplmTo0Lbg8AoN+aNADQDT5N2MMmqbJzz3Pg0eAMID7vAgSAcfg+6ILGIlS8eX7vsO4PzuZMN+2DOPvEyaMnccY8/+TAP3HAPnkk8+HeZ44njEczzmfKEeu+KJBNgxA14IBJ2lnNNCcNIGkXpeA6HrwO/hcwBUeCp4jD6UxHa7nw3NpfOk4OmzHCY4JwLJ0xGMxdLa3orY6gdbWZlFRmZyTy2RfjOjm83vvv//G/wQw/3ZAPv109XDOxZVC4DTGmElSHpijbk0wDB2mGQDi+R503ZDmSpolj0MzTKkR9LfEkUChYzAyWb7UEAIgncmisqIanZ2dsG1XnqNffR0K+Rxy2RS456J/fR+0tjbBcWxYuiHNHQBX+PxpnbFf73PIISv/ncD82wD5/POG8a7rXsUY+w75BJJ8Jd0k/TSenPvyt2WZEMKBYWiIx2NdGkDgWZaFznSn1A4CynVd5HI5pDpTyOUyyKQ7kMsV0NHRAcfxkc3kYJgG6uv7Y9y4sXQSNGxaj2GD+iPb0Y5sLovy6t5IpTKoqqyAU7AJe4AD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4Jv1BkIsK23x1IWFJCQ+sujC6COV4w9KnpE0626IPKqWWSmpVIBf2M+o76MEciu6bMGGgM9OGRI2FrEjh844l+MPbz8OJZVHTK4nekQE4ZNRx6GsNQ9SLdGVze/JbdP2lpqpLCIojW6oRasBVlpgAiUaj8Fy+sibdPm70jBlUjbHDa6eAfPbJJ9dms5lrKBLnxcIBJphkSWqwv0iaw0xI2X3l0NVFKtNGx1HapgY3DI4yJbQfbae0UdFedTzNpOSkD803EdEttGQaYdZwvL/0Dcxa/xx4TQE5cNhpDeNqpuGk8ReitzcYHlq6TFZYYNQ1hK8vnC0u1ZiwGVMjrdI6ASAxWaTh+P7Ppx9zxC1fGpAlc5fs4rr5pbqpRbjMmPoBY/E4GA+qRIiYBFIRnmFTMyH0WVCaE3bWYbMUdphKc3YGcKlzDWuoMhlSgjUypwKaTzOLOrJ+BxpSG/C3j15DZCDDitQC2FYKum9gj+T+mLHHuahy+sBmlFHojlGUxocBCfsudR89aUXpZ0pYaHaTfK7vUe7NTdsuG3Xk947cYcaxRw35ePbsxznnZwTRdHeJjpztL5nkCT Here is my HTML <form action="{% url 'profile' %}" enctype="multipart/form-data" method="post" class="pic-upload-form" id="form">{% csrf_token %} <div class="custom-file"> {% bootstrap_form form %} </div> <!-- Croppie area --> <div id="upload-demo"></div> <input type="hidden" id="image-data" name="imagebase64"> <button type="button" class="btn btn-outline-info btn-custom upload-result">save</button> </form> The last portion of my js where i bind the image data to a hidden input. $('.upload-result').on('click', function (ev) { $uploadCrop.croppie('result', { type: 'base64', size: 'viewport' }).then(function (src) { console.log(src); // bind the image data to the hidden inpu id image-data $('#image-data').attr('src', src); $('#form').submit(); }); }); And here is my view def user_profile_view(request): '''Handle the image of the user.''' if request.method == 'POST': form = UploadPicForm(request.POST, request.FILES) if form.is_valid(): profile = form.save(commit=False) # get the base64 image data profile.image = request.FILES['imagebase64'] profile.save() messages.success(request, 'your pic updated successfully.') return HttpResponseRedirect(reverse('learning_path_tracker:home')) else: # form's user field populated by current user form = UploadPicForm(initial={'user': request.user}) return render(request, 'users/uploadpic.html', {'form': form}) I think the image data is not a string that's why request.FILES raise error. But how can i solve this, thanks in advance. -
How to solve Unknow Field Error in Django
I am building a project a project by Django 2.0.2. What I want to do is making one of the fieldsets in admin page change automatically according to the database. Here is part of my code: models.py class Product(BaseModel): number=model.IntergerField("Food", null=True, blank=True, help_text="Food") @property def number(self): return 10 #just return a number for testing admin.py class ProductAdmin(admin.ModelAdmin): list_display=("number") fieldsets=(('<h1>Food</h1>'), {'fields':('number')}) When I refresh the admin page, it shows "Unkown fields (number) specified for Product. Check fieldset attribute of class ProductAdmin". I am new to Django and not sure about what goes wrong. In the admin.py, I have added "number" field but the error still exist. How can I solve it? Many Thanks and Happy New Year. -
Maintain concurrency in the user session
BY A NOVICE PROGRAMMER: Web application is being used with RFID card reader (as keyboard emulator). When the user scans the RFID card in the specific field, RFID reader pastes the card number and then hits enter by itself so that the form is submitted. Sometimes the user scans the card once and the reader detects it 2 times (contacted vendor but the reader does not support redetection delay kind of a thing). So on the backend, I have a view function which is executed when the user's form is submitted. From the view function, the card number is send to other 2-3 functions in order to complete all the processes. I checked the app logs and found that When the card is read 2 times, only 7-8 lines of code is being executed and before the condition is checked, due to scanning card 2nd time, the same functions are called again and the condition checking does not makes sense. What is the technical term which I should google in order to execute all the functions one by one without any interruption? Tried using conditions but did not work -
TypeError an invalid keyword argument for this function
Happy new year! ) i am newbie in Python trying to make forms field and have a problem My forms shows correctly at html but when i am trying to submit data and save it to db i have an error TypeError at /srdb/ 'send_date' is an invalid keyword argument for this function here is my code models.py class Srdb(models.Model): send_date = models.DateField() send_weight = models.IntegerField(default=0, validators=[MaxValueValidator(10000), MinValueValidator(100)]) track_code = models.CharField(default=None, blank=False, max_length=20) send_index = models.IntegerField(default=None, blank=False, validators=[MaxValueValidator(999999), MinValueValidator(100000)]) sender_fullname = models.CharField(default=None, blank=False, max_length=150) sender_dob = models.DateField() sender_adress = models.CharField(default=None, blank=False, max_length=400) receiver_index = models.IntegerField(default=None, blank=False, validators=[MaxValueValidator(999999), MinValueValidator(100000)]) receiver_fullname = models.CharField(default=None, blank=False, max_length=150) receiver_adress = models.CharField(default=None, blank=False, max_length=400) sender = models.ForeignKey(Dostavshik, on_delete=models.CASCADE, default=None, blank=False) def __str__(self): return str(self.id) forms.py class SrdbForm(forms.Form): send_date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='Дата Отправки') send_weight = forms.IntegerField(initial=0, validators=[MaxValueValidator(10000), MinValueValidator(100)], label='Отправленный Вес (граммы)') track_code = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'placeholder': 'Код Отслеживания Посылки'}), label='Трек Код') send_index = forms.IntegerField(validators=[MaxValueValidator(999999), MinValueValidator(100000)], widget=forms.TextInput(attrs={'placeholder': 'Индекс Почты Отправления'}), label='Индекc Отправления') sender_fullname = forms.CharField(max_length=150, widget=forms.TextInput(attrs={'placeholder': 'Отправитель'}), label='ФИО отправителя') sender_dob = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='Дата Рождения Отправителя') sender_adress = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'placeholder': 'Полный Адрес Отправителя'}), label='Адрес отправителя') # Получатель receiver_index = forms.IntegerField(validators=[MaxValueValidator(999999), MinValueValidator(100000)], widget=forms.TextInput(attrs={'placeholder': 'Индекс Почты Получения'}), label='Индекс Получателя') receiver_fullname = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Получатель'}), label='ФИО Получателя') receiver_adress = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'placeholder': … -
"Path for saving emails is invalid: None" in django
my project was running correctly but after that I made few apps I start my work on previous app but I'm trying to send email this time I'm getting this error and I'm not able to understand what's the problem, I tried to get email and console and it's working but when I use EMAIL_BACKEND = django.core.mail.backends.smtp.EmailBackend I get this error, can someone help to figure it out what's the problemthis is image of error link -
django pwa is not loading block contents while service worker added
While I was working with django pwa library in one of my django project outlined as this tutorial. When I added serviceworker.js as they proposed the layout was loaded online and offline but contents inside block contents didn't load. Code is exactly they described. Didn't paste code somewhere as this is a large code and I was converting my project to PWA after fully production running. Thank you for your kind help. Let me know my mistakes. -
How to use different session id for same user across different django project
i have 2 django projects running on different domains. Both are using same database and same models. One project is in 2.7 and other project is in 3.7. when user login into one domain, it log out user from other domain. How i can restrict him to not logging user out from one domain on login into another domain ? -
Django Celery - Creating duplicate users due to mutiple workers
I am facing a weird issue with celery in production. Currently, the production server has 4 celery workers which handle all the tasks registered by my django app. No custom queues are defined. The workers are basically 4 separate supervisor conf files. Now, in my app I am handling facebook webhook data, and I want a user with a specific FacebookID to be only created once on my backend. But, recently I checked and found out that there are users who have the same FacebookID, which should not have happened. What happened I think was e.g. user with FacebookID 666 sent me a webhook data. Now, a task is created which will create a new user instance in my database with FacebookID 666. Now, before the user is created in my database, the user hits me with another data, which also created a task but under a different worker, and thus I got myself two users with the same FacebookID. Is there any way I can configure celery to handle a user with a specific FacebookID to create tasks only in ONE worker? Or have I completely misjudged the situation over here? -
What's the best way to send and receive data using django?
I'm building an e-commerce site (and very new to django and python), and upon the user completing his online order, I want: the order to be sent to my office computer, where a pop-up will notify me The pop up will have 2 buttons, one will be "print invoice" and the other will be "order fulfilled" on pressing "order fulfilled", the django order model on the server will be updated so the specific order will be marked as "fulfilled". Is this doable? Is it too complicated? For step 1, I've read that sockets might be what I need to learn, but I don't know how it will work for step 3. Anyone have any suggestions? -
Fetching information from GET request in dictionary format
I have a html form in which for every option in a select element i can choose multiple values for that option from other select element.For example when i select 'page' then i have 'About','Contact', 'News','Cart' and 'Home' as select options.When i select 'items' then i have 'jeans','pants','hoodies','tshirts' and 'loafers' as options to select. For 'page' i select 'About','Contact' and 'News'.For 'items' i select 'jeans','pants' and 'tshirts'.After selecting these i click on Submit(where name='Save' for input type='submit'). Following is the GET request that i get to see on server side. HTTP GET /testPage/?key_name=page&key_value=About&key_value=Contact&key_value=Home&key_name=items&key_value=jeans&key_value=pants&key_value=tshirts&Save=Submit If i want to fetch information from this request i would do something like this: def myView(request): myKey = request.GET.getlist('key_name',) myKeyValue = request.GET.getlist('key_value',) #I am printing these fetched values just to know how the function works. print(str(myKey)+" , "+str(myKeyValue)) The above print function prints the following: ['page', 'items'] , ['About', 'Contact', 'News', 'jeans', 'pants', 'tshirts'] This printed statement shows that keys- 'page' and 'items' are assigned to myKey variable and values - 'About', 'Contact', 'News', 'jeans', 'pants'and 'tshirts' are assigned to myKeyValue variable. Is there any way that i can fetch information from the GET request in such a way that key values are attached to their … -
OperationalError at /admin/myschoolweb/album/add/ - no such table: main.auth_user__old
I am trying to add new data in table, but every time it gives below error Django Version: 2.1.4 Python Version: 3.7.1 Sqlite3 Version: 2.6.0 I have already gone through all the available answers here, but still the issue persists. I have already followed the steps for 'python manage.py makemigrations' , 'python manage.py migrate'. i tried to upgrade as well as "downgrade your version of sqlite to a version prior to 2.6 (e.g. 2.5.1)", but I don't know how to do this. Can anyone help. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/myschoolweb/album/add/ Django Version: 2.1.4 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myschoolweb'] Installed 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'] Traceback: File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\db\backends\utils.py" in _execute 85. return self.cursor.execute(sql, params) File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 296. return Database.Cursor.execute(self, query, params) The above exception (no such table: main.auth_user__old) was the direct cause of the following exception: File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\contrib\admin\options.py" in wrapper 604. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response … -
How to upgrade Django in visual studio
Is there any method to upgrade the Django and project to the latest version? Thanks, Saeed -
Training and Finetuning a model in AllenNLP
I want to train a model and also finetune it using AllenNLP in a django environment. I want to do these by using the functions(code) available in allennlp github repo. I don't want command line, rather want to pass arguments. How can I do this? Any help will be appreciated. -
From submitted twice
I wanted to upload any file. But when I submit the upload then same post is uploaded twice but in one of it there is no file but just the content and in next there is file. class FileCreateView(PassRequestMixin, SuccessMessageMixin, CreateView): template_name = 'file/upload-file.html' form_class = FileForm success_message = 'File was uploaded successfully' success_url = reverse_lazy('home') def post(self, *args, **kwargs): """ Handle POST requests: instantiate a form instance with the passed POST variables and then check if it's valid. """ # form = self.get_form([self.request.FILES]) form = self.form_class(self.request.POST, self.request.FILES) if self.request.method == 'POST': if form.is_valid(): file = form.save(commit=False) file.upload = form.cleaned_data['upload'] file.author = User.objects.get(pk=self.request.user.pk) file.save() return self.form_valid(form) else: return self.form_invalid(form) home.html <div class="container mt-3"> <div class="row"> <div class="col-12 mb-3"> <button class="upload-file btn btn-primary" type="button" name="button"> <span class="fa fa-plus mr-2"></span>Upload Form</button> </div> </div> {% block extrascripts %} <script type="text/javascript"> $(function () { $(".upload-file").modalForm({formURL: "{% url 'file-upload' %}"}); }); </script> {% endblock extrascripts %} urls.py path('upload/file/', FileCreateView.as_view(), name="file-upload"), model.py class File(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) visible_to_home = models.ManyToManyField(Home, blank=True) # when none visible to all home visible_to_company = models.ManyToManyField(Company, blank=True) # when none visible to all company # To determine visibility, check if vtc is none or include … -
How to run same project on different port/DNS using Apache2.4 & Windows
I am setting up a UAT and Live environment in a windows server using apache2.4 and mod_wsgi for my Django project. How can I run both projects on different ports/DNS using virtual host configuration? NOTE: I don't have any dedicated DNS that is mapped to the windows server's IP & I'm using the same project in both environments. -
How do I get a value for a non-pk field in a fk?
Good evening, I am relatively knew to Django but I am not understanding how I get a value for a different field referenced by a Foreign Key. For example, I have a model: class Status(models.Model): status_text = models.CharField(max_length=20) status_open = models.BooleanField(default=1) def __str__(self): return self.status_text class Target(models.Model): last_name = models.CharField(max_length=40) first_name = models.CharField(max_length=40) status = models.ForeignKey(Status, on_delete=models.CASCADE) I want to query it: queryset = Target.objects.filter(status__status_open=1) When I do this, I get returned the pk (1,2,3, etc.) for the status field. What I really want is the status_text that corresponds to that pk. I have been playing with select related but it just states that status_text is not a FK. Thanks for your help. I continue to struggle with the ORM in my usage of Django... -
static files django channels
I'have problem in my home page of notifications systeme. I'm follow this course https://arunrocks.com/understanding-django-channels/ this is my js code <script src="{% static '/channels/js/websocketbridge.js' %}" type="text/javascript"></script> <script> document.addEventListener('DOMContentLoaded', function() { const webSocketBridge = new channels.WebSocketBridge(); const nl = document.querySelector("#notifylist"); webSocketBridge.connect('/notifications/'); webSocketBridge.listen(function(action, stream) { console.log("RESPONSE:", action); if(action.event == "New User") { var el = document.createElement("li"); el.innerHTML = `New user <b>${action.username}</b> has joined!`; nl.appendChild(el); } }) document.ws = webSocketBridge; /* for debugging */ }) </script> in console this error is appears -
Django signal not working with django-paypal
I am trying to handle the signal valid_ipn_received from the package django-paypal (docs: https://django-paypal.readthedocs.io/en/stable/standard/ipn.html) engine/signals.py from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received from engine.models import DatasetRequest from django.views.decorators.csrf import csrf_exempt def show_me_the_money(sender, **kwargs): print('test') ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # WARNING ! # Check that the receiver email is the same we previously # set on the `business` field. (The user could tamper with # that fields on the payment form before it goes to PayPal) if ipn_obj.receiver_email != "paypalemail@gmail.com": # Not a valid payment return # ALSO: for the same reason, you need to check the amount # received, `custom` etc. are all what you expect or what # is allowed. if ipn_obj.mc_gross == ipn_obj.amount and ipn_obj.mc_currency == 'USD': pk = ipn_obj.invoice dsr = DatasetRequest.objects.get(pk=pk) dsr.is_paid = True dsr.save() else: pass valid_ipn_received.connect(show_me_the_money) engine/apps.py from django.apps import AppConfig class EngineConfig(AppConfig): name = 'engine' def ready(self): import engine.signals engine/views.py def pay_for_dataset_request(request, dsr_pk): # dsr_pk = dataset request primary key dsr = DatasetRequest.objects.get(pk=dsr_pk) paypal_dict = { "business": "paypalemail@gmail.com", "amount": dsr.reward, "item_name": dsr.title, "invoice": dsr.pk, "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return": request.build_absolute_uri(reverse('datasetrequest_detail', kwargs={'pk': dsr.pk, 'slug': dsr.slug})), "cancel_return": request.build_absolute_uri(reverse('datasetrequest_detail', kwargs={'pk': dsr.pk, 'slug': dsr.slug})), } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": … -
Django Queryset help, count items associated with item
I am making a web application for an inventory management application using Django. In this web app, storage boxes (with contents) are assigned to people in my database. I am trying to write a queryset that I could loop over (see my HTML) that would retrieve the total number of boxes assigned to each project e.g. Project: Project Green, Total Boxes: 5. Im having difficulty writing this. I've tried to use _Set for a revere lookup and the count function but I can't get anything to work. Could somebody point me int he right direction? I've simplified my code below. My model: class Box(models.Model): box_contents = models.CharField(max_length=300, blank=True, null=True) project_assigned_to = models.ForeignKey('Project', null=True) Location = models.OneToOneField('Location', null=True) class Project(models.Model): project_name = models.CharField(max_length=255, blank=False, null=True) My View: def page(request): project_data = Project.objects.all() return render(request, 'main_app/page.html' , {"project_data":project_data}) My HTML: {% for item in project_data %} <p>Project Name: {{ item.project_name }}</p> <p>Number of Boxes Assigned: {{ item.Box_set.box_contents.count }}</p> {% endfor %} -
Azure Deployment Automation
I'm sure this is a very elementary question... I've built my first Django app and have successfully deployed it to Azure's Web App service. However, after each new deployment, I have to login to the Azure Web SSH and run the following commands to setup the SQL Server connection: apt-get update apt-get install gnupg apt-get install apt-transport-https curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - curl https://packages.microsoft.com/config/debian/9/prod.list > /etc/apt/sources.list.d/mssql-release.list apt-get update ACCEPT_EULA=Y apt-get install msodbcsql17 Once completed, my app runs on Azure as intended. Is there a way to automate these commands so I don't have to manually run them after each deployment? I've read about docker images, but don't know if that's what I need? I'm new to web development, so I apologize in advance if this is a very basic/simple question. Thanks! -
Docker installing wrong django packages
Host Machine: WIndows 10 I created a django project that uses an sqlite database. I tried to put my django app in a container using the following dockerfile: FROM python:3.5 #Enviromental variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 #Work Dir ADD . /code WORKDIR /code # Install dependencies RUN pip install -r requirements.txt Dockercompose file: version: '3.7' services: db: image: postgres:11.1-alpine volumes: - pgdata:/var/lib/postgresql/data/ ports: - 5432:5432 web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db volumes: pgdata: Now, when I try to run the code it gives me this error: Starting iomweb_db_1 ... done Starting iomweb_web_1 ... done Attaching to iomweb_db_1, iomweb_web_1 db_1 | 2018-12-31 20:26:15.535 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2018-12-31 20:26:15.535 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2018-12-31 20:26:15.547 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL. 5432" db_1 | 2018-12-31 20:26:15.576 UTC [19] LOG: database system was interrupted; last known up at 2018 -12-31 19:58:19 UTC db_1 | 2018-12-31 20:26:16.655 UTC [19] LOG: database system was not properly shut down; automatic recovery in progress db_1 | 2018-12-31 20:26:16.662 UTC [19] LOG: redo starts at 0/17ABE00 …