Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django webhooks with braintree/PayPal
Anyone who have used webhooks to receive event, I have some confusion on implementing that. Suppose I register a hook to update an object, will my hook service(say stripe or PayPal) will automatically send me payload or do I need to have task scheduler to run those requests to update data? Any help or docs will be appreciated -
cannot auto create profile when registered new user from link
Problem : user's profile hasn't be created through "Sign Up" link(new user register) but able to created in only admin page. view.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.contrib.auth.decorators import login_required def register_view(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created!!!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register_users.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!!!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile_users.html',context) model.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='abc.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField(max_length=30) class Meta: model = User fields = [ 'username', 'email', 'password1', 'password2', ] class UserUpdateForm(forms.ModelForm): email = forms.EmailField(max_length=30) class Meta: model = User fields = [ 'username', … -
Python3 use imported module in function django
I upgrade from Djanjo 1.8 to 2.1 I noticed that when I try to use an imported module, the module is not found Example #1 from var_dump import var_dump from django.db import connection def get_answers(): with connection.cursor() as cursor: query = """SELECT * FROM `stackoverflow` ;""" cursor.execute(query) row = cursor.fetchone() return row var_dump(get_available_id()) This results in NameError: name 'connection' is not defined How ever if I import the connection module in the function get_answers everything works Example #2 from var_dump import var_dump def get_answers(): from django.db import connection with connection.cursor() as cursor: query = """SELECT * FROM `stackoverflow` ;""" cursor.execute(query) row = cursor.fetchone() return row var_dump(get_available_id()) This works. What can I do to make sure example #1 works with global import. I am running the code like this python manage.py shell < sql/import.py -
Django FileField saving file manually causes memory leaks
I'm using Django FileField in a model to save images, I'm using DRF (Django rest framework) for views. The use case I've is API would receive a request for signing up new users from social media platforms, the client sends us the profile picture URL retrieved from the platform (e.g Facebook), we'd then download the image from that URL and pass it to the serializer via context (using following code) and close file afterward (I'm using Amazon S3 for storage) [using Django = 2.0.6, python = 3.5, DRF=3.8.2] def get_user_image(data): try: url = data["image"] file_name = os.path.basename(urlparse(url).path) image_name = get_uuid() + '.jpeg' if not file_name else file_name temp_path = '/tmp/' + image_name urllib.request.urlretrieve(url, temp_path) stream = open(temp_path, "rb") file = File(stream) return {"name": image_name, "file": file} except Exception as e: file.close() return None def clean_temp_files(image): file = image['file'] file_path = image['name'] if file is not None: file.close() file_path = '/tmp/' + file_path os.remove(file_path) and in serializer we'd save the file. def create(self,validated_data): instance = super(UserSerializer, self).create(validated_data) instance.avatar.save(image["name"], image["file"], save=True) The problem is I'd run into memory leaks (I suspect that is the case) when the application gets deployed, I've deployed my application on a linux machine with nginx and uwsgi, … -
Is there a break template tag in Django I can use
I am running a for loop to find an image, but I want to block the for loop after it has found an image. I have found this website that seems to solve my problem but doesn't seem to be updated for Django 1.10.5: https://djangosnippets.org/snippets/2093/. {% for article in object_list %} {% if article.get == true %} <div id="tagHeader" style="background: url({{ article.get_thumbnails|varkey:'grid_thumb' }}) no-repeat center center fixed;"><!-- background image not working becuase home_background isn't in CMS --> {% else %} <div id="tagHeader" style="background: url({% static 'publicnfx/images/baconburger.jpg' %}) no-repeat center center fixed;"> {% endif %} {% endfor %} Does anyone know another solution for this? -
Django: can't access values of dictionary in template
I have a view with the following code: @login_required def grouping(request, project_id): groups = {} order = {} # Bind parameters to variables and return a 404 if one is considered incorrect for i in range(1, 5): if request.GET.get('filter%i' % i, None) is not None: try: order[i] = int(request.GET.get('filter%i' % i, None)) except ValueError: return projects_overview(request, 'Incorrect filter parameters passed', 404) if order == {}: return projects_overview(request, 'Incorrect filter parameters passed', 404) original_properties = [] # Put all of the originally passed properties in a list for key in order: property = Property.objects.get(pk=order[key]) original_properties.append(property) # Get the corresponding category and project category = original_properties[0].category project = Project.objects.get(pk=project_id) objects = Object.objects.filter(project=project, type__category=category) # Group the objects with the same property values together for object in objects: properties = object.property_set.all().order_by('name') values = [] for property in properties: if property.original_property in original_properties: values.append(property.value) values_json = json.dumps(values) if groups.get(values_json) is None: groups[values_json] = [] groups[values_json].append(object) print(groups) return render(request, 'dashboard/groups.html', {'groups': groups, 'project': project, 'function_create_form': ObjectForm(project_id=project_id)}) The problem is the variable groups, which returns something like this: {'["a", "b", "c"]': [<Object: Object 3>, <Object: Object 4>], '["q", "w", "e"]': [<Object: Object 5>]} Now I am trying to iterate over this in my template: {% for … -
Rollback DB with real data when using pytest-django, pytest-splinter and pytest-bdd
For BDD of our Django project, we combine pytest-splinter with py-test django (and pytest-bdd). We run our test on real data. Therefore, we would like all changes made to the DB rolled back after each test, or alternatively after all tests. Our question: What's the correct way to use a real DB have proper rollback after browser testing ? Where we are thus far: We overwrite the py.test django_db_setup fixture as follows in conftest.py: @pytest.fixture(scope='session') def django_db_setup( request, django_test_environment, django_db_blocker, django_db_use_migrations, django_db_keepdb, django_db_modify_db_settings, ): return When not using the py.test live_server fixture, DB changes made via the browser are not rolled back, and accumulate in our DB. @scenario('user_management.feature', 'Add a new user') def test_add_a_new_user(db): pass When using the py.test live_server fixture we get an error that the DB tables cannot be flushed (which is not the behavior we would like). @scenario('user_management.feature', 'Add a new user') def test_add_a_new_user(db, live_server): pass This is the error: django.db.utils.NotSupportedError: cannot truncate a table referenced in a foreign key constraint django.core.management.base.CommandError: Database carbon-delta-lab couldn't be flushed. Thanks a lot for your help! -
Celery.schedules crontab - How to schedule a task to occur ONCE in a specific range of hours?
I need a celery task to be run on 2 specific days of the week between the 9th and 11th hour. day_of_week = '2,5', hour = '9-11' Does setting the parameter as above run the task every hour within the 9-11 range? How should I modify it such that it is run just once in this hour range? Is it possible to set a range or should I specify a timing? -
how to send an array field for django?
I have an API that needs to receive a file and an array field in the same time so a can't use application_json for CONTENT_TYPE of my request. I've used many ways to do this: 1- send via post man with two fields with the same name 2- send it via indexed names like this. array_field[0]=0 array_field[1]=1 3- send it like this array_field[]=0 array_field[]=1 when i want to retrieve the list via: request.POST.getlist("recipients[]") or request.POST.getlist("recipients") in django i get empty_list it or i get a list with the last item i have sent. how can i do this? thanks in advance. -
How to make 2nd drop down list auto select value based on 1st drop down value
I have two drop down list, one for Client and Location. I would like the location drop down to auto select a value based on the selected Client option. This is the script i came up with but the value is not being displayed on the location drop down. function defaultLocation () { var client2 = document.getElementById('clientList2'); if (client2.value == "Arm") { document.getElementById('locationList2').value == "Cambridge"; } } As of now, I want the value to be auto selected when the Client option is chosen with no need to click a button. -
reason behind "local variable 'variable ' referenced before assignmen" ERROR
I am not much familiar with django. Was working on a learning project. So here I am getting the error which says UnboundLocalError, "local variable 'url_array' referenced before assignment" . Here's my form.py , views.py and html code. Please have a look and give me a solution. forms.py from django import forms from .models import Images class ImageForm(forms.ModelForm): class Meta: model = Images fields = ('__all__') views.py class Upload(View): def post(self, request): form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() imageZip=request.FILES fs = FileSystemStorage() url_array = [] with ZipFile(imageZip['image'], 'r') as zip: zip.extractall() unzip_file= zip.namelist() for files in unzip_file: with open(files, "rb") as file: name = fs.save('read.jpg', file) url_array.append(fs.url(name)) else: form = ImageForm() return render(request, 'toDo_app.html', context = {'form': form, 'url':url_array}) toDo_app.html <form class="" enctype="multipart/form-data" action="/upload/" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" >Upload</button> </form> <br> {% if url %} <p>Uploaded file: </p> <ul> {% for urls in url %} <li> <a href="{{ urls }}">{{ urls }}</a> </li> {% endfor %} </ul> {% endif %} So my error is at return render(request, 'toDo_app.html', context = {'form': form, 'url':url_array}) line. Thanks for your time and I would be really grateful for an explanation and solution -
How to prevent the logged in user to access the profile of other user by simply changing the id in url , in django?
i'm currently building a small project using django, i have noticed a problem that a logged in user was getting access to the other users page by simply changing the id in the url i.e This is the url of currently logged in user http://localhost:8000/home/myBooks/7/ by changing that id from 7 to 6 i.e http://localhost:8000/home/myBooks/6/ He was getting access to that page,i have used @login_required for functional based views and LoginRequiredMixin for class based views ,but they are not helping, what else i need to do to prevent this problem? -
Uploading image through an upload form to Django User profile
I am trying to create a student register page that allows the student to upload a profile photo. I'm using Django User model and a StudentProfile model that has a one-to-one relation with User. Here are my codes: student\models.py: from django.db import models from django.contrib.auth.models import User class StudentProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,) avatar = models.ImageField(upload_to='student_profile/', null=True, blank=True) def __str__(self): return self.user.username students/form.py: from django import forms class ImageUploadForm(forms.Form): profile_photo = forms.ImageField() eLearning/views.py: from django.contrib.auth import authenticate, login, get_user_model from django.http import HttpResponse from django.shortcuts import render, redirect from .forms import LoginForm, RegisterForm from students.forms import ImageUploadForm from students.models import StudentProfile User = get_user_model() def register_page(request): register_form = RegisterForm(request.POST or None) photo_upload_form = ImageUploadForm(request.POST, request.FILES) context = { "register_form": register_form, "photo_upload form": photo_upload_form } if register_form.is_valid(): # print(register_form.cleaned_data) username = register_form.cleaned_data.get("username") first_name = register_form.cleaned_data.get("first_name") last_name = register_form.cleaned_data.get("last_name") email = register_form.cleaned_data.get("email") password = register_form.cleaned_data.get("password") new_user = User.objects.create_user( username, email, password, first_name=first_name, last_name=last_name, ) if photo_upload_form.is_valid(): user = username avatar = photo_upload_form.cleaed_data.get("profile_photo") new_user_profile = StudentProfile.objects.create(user, avatar) print(new_user) return render(request, "auth/register.html", context) auth/register.html: {% extends "base.html" %} {% load static %} {% block content %} {% load crispy_forms_tags %} <div class="container"> <div class="row my-4"> <div class="col-5"> <form action="" method="post" class="form-control"> {% csrf_token %} … -
serializer.DictField does not save to database
I have this model: class x(model.Models): name = models.CharField(max_length=50, unique=True) y = models.ManyToManyField(Y, related_name='y', db_table='x_y', blank=False,null=False) and this serializer: class Serializer(DynamicFieldsModelSerializer): class Meta: model = models.x fields = '__all__' when I post data to this model I need to set this fields: 'name':['some name'],'y':['1','2'] this will make a row in database x with: id | name 1 | some name and two row in database x_y with: id| x_id | y_id 1 | 1 | 1 2 | 1 | 2 the problem is that front end dose not send me 'name' and 'y' ,but send me 'name' and 'y[]', so in order to get data I needed to add this to my serializer class: y= serializers.DictField(child=serializers.IntegerField(min_value=0, max_value=2)) but the result is that no data will save in x_y table.I dont know how to solve this -
How to fix djangos's decotators Error: Wrapped class must subclass ModelAdmin
I have been whriten API for my app. End when I to start servver terminal cought this: ValueError: Wrapped class must subclass ModelAdmin.I'm new with django... How to fix that? -
How to use case insensitive in operation in django orm?
User.objects.filter(name__in=["A", "AB", "a", "ab", "Ab"]) This is an example of using in field lookup in Django. But I want to know that is here any trick of using in as case insensitive like icontains ? Thank you -
Get query string variable name in Django
I am new to Django, so my problem might be simple. I need to write a template, that would echo information from a query string. The string looks something like that: http://127.0.0.1:8000/echo/?a=1 The problem is, that query name might change from 'a' to something else, and I need to echo it accordingly. I know how to capture value from that string, but I don't know how to capture name. Please help. def echo(request): return render(request, 'echo.html', context={ 'get': request.GET.get('a'), 'post': request.GET.get('b') }) <!--DOCTYPE html --> <html> <body> {% if request.method == 'GET' %} <h1> get a= {{ get }} statement is empty </h1> {% elif request.method == 'POST' %} <h2> post b= {{ post }} statement is empty</h2> {% endif %} </body> </html> -
handle multiple ForeinKeys in one field _ Django
suppose we have a Model A that has relations ForeinKey to Model B. class B(models.Model): ..... class A(models.Model): foo = models.ForeinKey(B) how can I have an instance of A model that has dozens of foo ? and a proper solution I need for that. is that possible? I think this is dummm if we made many foo fields. so is it possible in django to handle this type of problems? -
How to create django subdomains
How will I create django subdomains for user accounts that can return user information even if the user isn't logged in. For example jane.website.com returns jane's page even though jane isn't logged in. I've tried django-subdomains but it keeps giving me this error 'Module not found error :No module named 'django.core.urlresolvers'. I'm pretty sure the error is from django-subdomains so I rather use something else. Any suggestions? -
Different browsers access the same view ,generate different cacahe ,why?
my english is not well. django use redis-cache then two browser access the same view,after one.but redis have two key cache. uels.py: path("api/overview/",cache_page(60*15)(views.OverView.as_view()),name="overview") setting: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "KEY_FUNCTION": lambda key, key_prefix, version: "django:" + key, "TIMEOUT": 60 * 60, "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } redis: 1) "django:views.decorators.cache.cache_page..GET.764bc7c41cef3ce80d301c9cc0e7cb37.d41d8cd98f00b204e9800998ecf8427e.zh-hans.Asia/Shanghai" 2) "django:views.decorators.cache.cache_header..764bc7c41cef3ce80d301c9cc0e7cb37.zh-hans.Asia/Shanghai" 4) "django:views.decorators.cache.cache_page..GET.ea62c22ccdba8dfc927e62ae2fbc92e7.d41d8cd98f00b204e9800998ecf8427e.zh-hans.Asia/Shanghai" 5) "django:views.decorators.cache.cache_header..ea62c22ccdba8dfc927e62ae2fbc92e7.zh-hans.Asia/Shanghai" i have a question :"ea62c22ccdba8dfc927e62ae2fbc92e7" how generate? thinks! -
How to handle N812 lowercase 'ugettext_lazy' imported as non lowercase '_' of pep8-naming
It is very common to import 'ugettext_lazy' as '_'. New version of pep8-naming does not like this. How to handle this? -
I want to change django's login settings,(base.py) but I don't know why an error occurs (jwt setting)
I'm changing the Django login settings to implement Facebook login with jwt By the way There was a little problem. ACCOUNT_EMAIL_REQUIRED = True => ACCOUNT_EMAIL_REQUIRED = False This causes an error An error occurs when the server starts by python manage.py runserver The contents of the error are as follows. Line 12, in <module> \ bin \ lib \ site-packages \ allauth \ account \ models.py "file" C: \ Users \ hyunsepk \ AppData \ Local \ conda \ conda \ from. import app_settings, signals File, "line 324, in <module>", "file" C: \ Users \ hyunsepk \ AppData \ Local \ conda \ conda \ envs \ fast2 \ lib \ site-packages \ allauth \ account \ app_settings.py " app_settings = AppSettings ('ACCOUNT_') App_settings.py ", line 28, in __init__ file_location \ con \ conda \ envs \ fast2 \ lib \ site-packages \ allauth \ account \ app_settings.py or self.EMAIL_REQUIRED AssertionError Thank you very much for letting me know the cause of the problem or how to solve it. github : https://github.com/hyunsokstar/hyun4/tree/master/nomadgram -
Pagination on get_context_data() - Django
How can i do pagination on get_context_data(). Previous i was using get_queryset() but in am querying two models. So how can i do it class UserListView(LoginRequiredMixin, generic.TemplateView): template_name = 'users/users.html' paginate_by = 1 def get_context_data(self, **kwargs): context = super(UserListView, self).get_context_data(**kwargs) context['companies'] = Company.objects.exclude(company_is_deleted=True).exclude(company_name='Apollo') context['users'] = User.objects.exclude( Q(userprofile__user_role__acl_role_title='Super Admin') | Q(is_superuser=True) | Q(userprofile__user_is_deleted = True)| Q(userprofile__user_company__company_is_deleted=True) ) query = self.request.GET.get('query') if query: list_query = context['users'] context['users'] = list_query.filter(userprofile__user_company__company_name__icontains=query) return context -
Design approach for Multiple choice quiz app with Multiple right answers
Hi I'm trying to implement a django quiz app. But can't figure out the approach i should use when trying to create a question with multiple right answers. ie, users should be able to mark multiple choices as the right answers. This is what I've come up with so far. class Question(models.Model): question = models.CharField(...) class Choice(models.Model): question = models.ForeignKey("Question") choice = modelsCharField("Choice", max_length=50) class Answer(models.Model): question = models.ForeignKey("Question") answers = models.ForeignKey("Choice") Please guide me how to implement it the right way. -
How to integrate VueJS with Django and deploy them
I'm beginner in frontend development. I'm trying to use VueJS for my new Django project. And I'm thinking about how to integrate Vue with Django. I have been looking up and seems like there are two ways to do it. First way is to include Vue files inside static/js folder. (like as we do with jquery) and templates is also included inside djnago project. And the second way is using webpack and creating another frontend folder outside Django project. templates is included inside Vue components. My first question is for the second way, how I can deploy the project? For local dev, I need to run Django project and Vue part separately and I'm wondering how I can deploy them later. Also, which way is better? What is the advantages and disadvantages of each way?