Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest frame work filter a serializer field
i had django api and its serializer and models... i use filters like this: class OrderFilter(django_filters.FilterSet): class Meta: model = Dealer fields = { 'first_name': ['icontains', 'exact'], 'last_name': ['icontains', 'exact'], 'mobile': ['icontains', 'exact'], 'is_active': ['exact'], 'agent': ['exact'], } all of this fields was django model field but in my serializer i have a SerializerMethodField like this: class DealerListSerializer(serializers.ModelSerializer): online = serializers.SerializerMethodField() def get_online(self, obj): r = Redis.get_instance().conn key = settings.ONLINE_PREFIX.format(obj.id) if r.get(key): return True return False i would like to apply filter on online field. class OrderFilter(django_filters.FilterSet): online = django_filters.rest_framework.BooleanFilter(method='filter_online') def filter_online(self, queryset, name, value): ????? class Meta: model = Dealer fields = { 'first_name': ['icontains', 'exact'], 'last_name': ['icontains', 'exact'], 'mobile': ['icontains', 'exact'], 'is_active': ['exact'], 'agent': ['exact'], 'online': ['exact'], } what should I do? thanks -
to separate search keyword with its response of google search api
Am having many cases here. in google API i first tried sending restricted site parameter suppose 'companysite' and query parameter as 'keyword' then i get response which can be stored easily as for keyword and company name but this type of call increases my api call if am having companysite with many keywords assigned to it,suppose am having a company having 4 keywords to it then i have to give 4 separate api call ,to over come it i used allintext:("keyword1" OR "keyword2")"Weber Automotive" for which i get some api response,but google api gives mixed response for both keywords then how to differenciate the keyword with its response? kindly help -
Django - Q Object much slower than doing separate queries
I have the following model: class Address(models.Model): full_address = models.CharField(max_length=80, db_index=True) alternative_address = models.CharField(max_length=80, db_index=True) I'm querying for a particular address, which can either match full_address or alternative_address. The obvious solution is to use a Q object. But for some reason, using a Q object makes the query much slower. address = '123 Main Street' # This query using Q object takes 500ms (10x slower) addresses = Address.objects.filter(Q(full_address__startswith=address) | Q(alternative_address__startswith=address)).values(...) # This solution, which returns the same results, takes just 50ms addresses1 = Address.objects.filter(full_address__startswith=address) addresses2 = Address.objects.filter(alternative_address__startswith=address) addresses = (addresses1 | addresses2).values(...) Is this supposed to happen? I think using a Q object in this case should be faster, not slower, right? -
Some static images are not loading in Django Templates
I'm working on a project using Django(1.10) in which I need to load some images in Django templates, But I'm wondering some images are loading but some are not loading even exists in the static_root folder. Here are my models: class AddedFile(models.Model): image_name = models.CharField(max_length=3000, blank=True, null=True) file_name = models.CharField(max_length=3000, blank=True, null=True) def __str__(self): return str(self.id) class Products(models.Model): name = models.CharField(max_length=100, blank=True, null=True) description = models.TextField(max_length=200, blank=True, null=True) image = models.ForeignKey(AddedFile, on_delete=models.CASCADE, null=True) category = models.ForeignKey(Categories, on_delete=models.CASCADE, null=True) parent_product_id = models.IntegerField(null=True) product_type = models.CharField(max_length=100, blank=True) regular_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) sale_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) quantity = models.IntegerField(default=0) sku_no = models.CharField(max_length=100, blank=True, null=True) variant = models.CharField(max_length=100, blank=True, null=True) tax_able = models.BooleanField(default=False) enable_flag = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.id) Here's from views.py: def product_add(request): user_type = '' try: user_type = request.session['user_type'] except Exception as e: print(e) if user_type == 'admin': if request.method == "POST": try: cat_id = request.POST['cat_id'] description = request.POST['description'] img = request.POST['img'] name = request.POST['name'] product_type = request.POST['product_type'] tax_able = request.POST['tax_able'] if product_type == 'simple': regular_price = request.POST['regular_price'] sale_price = request.POST['sale_price'] sku = request.POST['sku'] quantity = request.POST['quantity'] if img: get_img = [] try: directory_base = settings.STATIC_ROOT image = img.split(";base64,") extens = … -
select languages using django get_available_languages
I have a portal language field i want dropbox to select the language.can we use django get_available_languages to implement this. models.py class OtherDetails(models.Model): portal_language = models.CharField(max_length=128) forms.py class OtherDetailsForm(forms.ModelForm): widgets = { 'portal_language': forms.TextInput(attrs={'placeholder': _('Portal language')}), } template.html {{ otherdetails_form.as_p }} -
Assigning current 'User' as foreign key to nested serializers
I am trying to assign current 'User' to two models using nested serializers. class UserAddressSerializer(serializers.ModelSerializer): class Meta: model = UserAddress fields = ('user', 'address_1', 'address_2', 'country', 'state_province', 'city', 'zip_code') class UserProfileSerializer(serializers.ModelSerializer): user_address = UserAddressSerializer() user = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = UserProfile fields = ('user', 'first_name', 'middle_name', 'last_name', 'title', 'display_name', 'time_zone', 'user_address', 'default_office') def create(self, validated_data): user = validated_data.pop('user') user_address_data = validated_data.pop('user_address') user_address_object = UserAddress.objects.create( user=user, **user_address_data) user_profile_object = UserProfile.objects.create( user=user, **validated_data) return user What I am getting is this output in Postman. { "user_address": { "user": [ "This field is required." ] } } I want to know a way to pass 'User' to both of these model creation. -
Django create fallback database if entry does not exist in one
Right now, I have two databases, english and native. The functionality I'm trying to achieve is, if an entry does not exist in my native database, it should fall back to the english database to retrieve the data. I know I can do this by explicitly specifying the database name followed by a couple of try except blocks but I was wondering if there was a way to directly configure the database router to do this for me. -
Django - Query based on model fields combined together
Assuming we have an Address model with details of a particular address: class Address(models.Model): street = models.CharField(max_length=100) city = models.CharField(max_length=100) Let's say we want to filter for the following address: my_address = 123 Main Street Toronto Is there some way to combine street and city to perform a query? Like: Address.objects.filter(street + ' ' + city=my_address) This is just an example. Please do not suggest an alternate solution like splitting my_address into street and city. -
what is the best way to do django relational?
I just learn to program Django, and until now when creating models and relation i always write it like this : class Car(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Factory(models.Model): name = models.CharField(max_length=30) car = models.ForeignKey(Car, on_delete=models.PROTECT, null=True) def __str__(self): return self.name but now my models seems cant used when im learning to use admin.StackInline to add extra car when i want to add new data for factory in my admin, is there any problem with my code? what is the best practice for relating a models in Django? thanks -
How create your custom auth system in django?
I want to create login, register and other pages for authentification, but without using User model and not extending it(this is necessarily). How can I do these type of things in django? I'm asking because I can't find any sources with answers for this question, and also I'm just started using django? -
Django CKEditor: ModuleNotFoundError when deploying to Heroku
I'm getting an error in my logs when deploying my Django application to Heroku, but only when using the django-ckeditor package. CKEditor runs just fine locally, and earlier versions of the application work fine both locally and on Heroku without CKEditor, so I know that's the problem. I've retraced my steps and can't figure out where I went wrong. Here are my following logs... Heroku Logs 2018-12-10T03:03:16.513649+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load 2018-12-10T03:03:16.513651+00:00 app[web.1]: return self.load_wsgiapp() 2018-12-10T03:03:16.513652+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp 2018-12-10T03:03:16.513654+00:00 app[web.1]: return util.import_app(self.app_uri) 2018-12-10T03:03:16.513656+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app 2018-12-10T03:03:16.513657+00:00 app[web.1]: __import__(module) 2018-12-10T03:03:16.513659+00:00 app[web.1]: File "/app/JayNautic/wsgi.py", line 16, in <module> 2018-12-10T03:03:16.513660+00:00 app[web.1]: application = get_wsgi_application() 2018-12-10T03:03:16.513662+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2018-12-10T03:03:16.513664+00:00 app[web.1]: django.setup(set_prefix=False) 2018-12-10T03:03:16.513665+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/__init__.py", line 24, in setup 2018-12-10T03:03:16.513667+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2018-12-10T03:03:16.513669+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/registry.py", line 89, in populate 2018-12-10T03:03:16.513670+00:00 app[web.1]: app_config = AppConfig.create(entry) 2018-12-10T03:03:16.513672+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/config.py", line 90, in create 2018-12-10T03:03:16.513674+00:00 app[web.1]: module = import_module(entry) 2018-12-10T03:03:16.513675+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module 2018-12-10T03:03:16.513677+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2018-12-10T03:03:16.513718+00:00 app[web.1]: ModuleNotFoundError: No module named 'ckeditor' 2018-12-10T03:03:16.514092+00:00 app[web.1]: [2018-12-10 03:03:16 +0000] [10] [INFO] Worker exiting (pid: 10) 2018-12-10T03:03:16.517239+00:00 app[web.1]: 2018-12-10T03:03:16.518081+00:00 app[web.1]: [2018-12-10 03:03:16 … -
How to Set up Visual Studio Code to Debug Requests with python and Django?
Python:3.3.5 Django: 1.8 IDE: VSCode Server:Apache 2.4 Mod_wsgi:4.4.6 Test tool:Postman My project like this: /A /B /subfolder test.py manage.py settings.py launch.json: { "name": "Django test", "type": "python", "request": "launch", "console": "integratedTerminal", "pythonPath": "C:/Python33/python.exe", "program": "${workspaceFolder}/B/manage.py", "args": [ "runserver", "--noreload", "--nothreading" ], // "debugOptions": [ // "WaitOnAbnormalExit", // "WaitOnNormalExit", // "RedirectOutput", // "DjangoDebugging" // ], "django": true }, manage.py: if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) I try to set breakpoint at test.py but not working, it can not stop at the breakpoint, I ensure the server is runing and test.py can work, and terminal output don't show error message. When I used postman to post, the status is 200,and test.py return my string "ok". -
How do I increase the max length of captured Python parameters in Sentry?
I'm using sentry-python==0.5.3 in a Django project, and when I inspect a stacktrace's parameter list, I see some of the values are long enough to be cut off by a ... elipsis. I want to see the entire value. How do I configure sentry-python to show the entire parameter value in the stacktrace? Here's how I'm calling the init function in my Django config: sentry_sdk.init( dsn="sentry dsn", integrations=[DjangoIntegration()], send_default_pii=True ) -
Django; Signup form with only email and password
I want to create a Sign Up form with just email and password (and confirmation). I don't need username. But when I try to create a CustomSignUp form based on UserCreationForm, this error occurred. Unknown field(s) (password2, password1) specified for CustomUser Do I have to set password fields? Or is there a smart way to inherit these (including validation) from UserCreationForm? forms.py class CustomUserCreationForm(UserCreationForm): class Meta: fields = ('email', 'password1', 'password2') and views.py is going to be like this def sign_up(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') password = form.cleaned_data.get('password1') user = authenticate(email=email, password=password) login(request, user) ... What is the easiest way to create like sign up form or login form with only email and password? -
Django Admin use JWT
Using: Django 1.11 Python 3.6 DRF with JWT in FE I understand that the Django admin uses a session, and basic authentication. What I did so far: Replaced the Django Admin authentication signin page with AWS-Cognito: The user goes to domain/admin/*, redirected to signin in AWS On successful signin the user is redirected to the redirect_uri, leads to a Django View In the view I replace the code with tokens I can't navigate to any Admin page - I am trying to redirect, but that doesn't work since I didn't login() the User Stuck - I would like to associate the User with the fetched tokens and authenticate with every Admin page request, and when the user logs out delete the tokens What to do next? When I use JWT with the Front End application, every request.META has HTTP_AUTHORIZATION, and uses a suitable backend. I know how to add backends, and potentially leverage the user.backend (I also use Cognito-JWT for other FE portions, so already wrote BE for that) I need to find a way to replace the Django Admin sessions authentication with the fetched token Thank you! -
How to Redirect Form Submissions to Another View
I have the following django form, which will be used by users to input a query and select a model to search that particular query: from django import forms class search_forms(forms.Form): search_query = forms.CharField(label='search_query') path_choices = [('urlpath1/','model name 1'), ('urlpath2/','model name 2')...] model_paths = forms.ChoiceField(label='model_paths',choices=path_choices) This form is used to populate a template which consists of a input field of text for for users to submit queries, and a drop down field which identifies which model the query should be directed to (the path_choices variable in forms.py). Thew views.py is as follows, which needs to change to the following somehow: def search(request): if request.method == 'GET': form = search_forms(request.GET) if form.is_valid(): return render(request, 'template_for_model_paths.html', {'form': form, 's_results': s_results}) else: form = search_forms() return render(request, 'search.html', {'form': form,}) Currently, the form template yields a GET result as follows: /search?search_query=QUERY&model_paths=model_path%2F What I would like to accomplish is: model_path/Query as the result, which I can feed back to the view for the search form and use it to redirect the view relevant for model_path. How should I accomplish this? Does this approach make sense? Or am I misapplying the intent of the form functionality? -
Automatic Thermal Receipt Printout with Python/Djano?
A restaurant currently has an online ordering system built with django, they get online orders via email but would like them to be automatically printed out as they come in. Is there a way to do this using python/django? Would I need to write code specific to the make/model of the printer? -
Django REST - Writing a view function that returns attributes changed on PATCH request
I'm trying to add a function to a view class of viewset.ModelViewSet such that when the user makes a patch request it returns the value and the attribute changed. So for example if I make a patch with the body like so {key : food, value : "coffee"} if the change was successful in the database the response should be 200 body: {food : "coffee"} How do I do this? Thanks in advanced. -
Creating a docker image to scaffold django projects
I'm build a docker image that can scaffold out a docker project using this Dockerfile: FROM python:3 WORKDIR /usr/src/app CMD ["pip","install Django"] CMD ["django-admin", "startproject hello_world_django"] I build the image using: docker build django-scaffold . and run it using docker run django-scaffold Error message: docker: Error response from daemon: OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"django-admin\": executable file not found in $PATH": unknown. When I run this docker image, I am informed that the command django-admin is not available. How can I add django-admin to the path within the container? -
Django ModelForm error 'this is a required field'
When trying to upload an Image in my Django App, I get the error "This is a required field". Even though I am actually uploading an Image. It works fine in the Admin, but not in the App itself. Here is the models.py, forms.py and the View, respectively. models.py class Blog(models.Model): BLOG_CATEGORIES = ( ( 'T', 'Technology'), ( 'B', 'Business' ), ( 'C', 'Culture' ), ( 'N', 'None' ) blogger = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.Cascade) date_added = models.DateField(auto_now_add=True) blog_post = models.TextField(max_length=2000) blog_category = models.CharField(max_length=20, choices=BLOG_CATEGORIES blog_name = models.CharField(max_length=20, primary_key=True) blog_picture_context = models.ImageField(upload_to='/static/homepage/', max_length=250) def __unicode__(self): return '{} created this entry on {}'.format(self.blogger, self.date_added) def __str__(self): return '{} created this entry on {}'.format(self.blogger, self.date_added) forms.py class BLogForm(models.ModelForm): class Meta: model = Blog fields = ['blogger', 'date_added', 'blog_post', 'blog_category', 'blog_name', 'blog_picture_context'] views.py class BlogView(LoginRequiredMixin, FormView): template_name = 'blog_form.html' form_class = BlogForm success_url = '/' login_url = 'users/login/' Again, just for context, I am trying to do this in the app with the development server running. It gives me the error just above the ImageField. !https://i.imgur.com/M7ylwzB.png -
Issue with deploying geodjango on heroku
I made a simple GIS application with GeoDjango and I am struggling to deploy it on Heroku. I tried with Heroku-18 stack with heroku config:set BUILD_WITH_GEO_LIBRARIES=1 but it got [Errno 2] No such file or directory: 'gdal-config': 'gdal-config' error. I also tried heroku-16 with https://github.com/cyberdelia/heroku-geo-buildpack.git buildpack but ended up with getting this error ImportError: libjasper.so.1: cannot open shared object file: No such file or directory. My requirements.txt is as below: beautifulsoup4==4.6.3 certifi==2018.11.29 chardet==3.0.4 dj-database-url==0.5.0 django-crispy-forms==1.7.2 django-heroku==0.3.1 django==2.1.4 gdal==2.1.3 gunicorn==19.9.0 idna==2.7 psycopg2==2.7.6.1 pytz==2018.7 requests==2.20.1 urllib3==1.24.1 whitenoise==4.1.2 wikipedia==1.4.0 I am also using python 3.7.0. Can you please help me? -
How can I fix Python/Django migrate error
I had migrated error. Please give me any advance thanks. And here is my related cod and error. migration/0001_initial_.py operations = [ migrations.CreateModel( name='Member', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=120)), ('content', models.TextField()), ], ), ] member models.py `class Member(models.Model): name = models.CharField(max_length=120) content = models.TextField() def __str__(self): return self.name` member serialize class class MembersSerializer(serializers.ModelSerializer): class Meta: model = Member fields = ('id', 'name', 'content') migrate result error AttributeError: 'AutoField' object has no attribute 'api' -
Django Rest Framework url dispatcher
I am trying to interact with the SWAPI API. I want a view that fetches all the movies(films/) and one that fetches one (film/id). When I hit http://127.0.0.1:8000/api/films/?id=4 it enters the get_films function. I am using Django==1.11 and Django Rest Framework==3.9.0 . my urs.py: urlpatterns = [ url(r'films/',views.get_films,name="get-films"), url(r'films/(?P<id>[0-9])/',views.get_film,name="get-film"), ] my views.py: MAX_RETRIES = 5 API_URL= "https://swapi.co/api/" @api_view(['GET', 'POST']) def get_films(request): request_url = API_URL + "films" print(request_url) if request.method == "GET": attempt_num = 0 # keep track of how many times we've retried while attempt_num < MAX_RETRIES: r = requests.get(request_url, timeout=10) if r.status_code == 200: data = r.json() return Response(data, status=status.HTTP_200_OK) else: attempt_num += 1 # You can probably use a logger to log the error here time.sleep(5) # Wait for 5 seconds before re-trying return Response({"error": "Request failed"}, status=r.status_code) else: return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'POST']) def get_film(self, request): print('entered') request_url = API_URL + "films/" + request.query_params.get('id') if request.method == "GET": attempt_num = 0 # keep track of how many times we've retried while attempt_num < MAX_RETRIES: r = requests.get(request_url, params=film_id,timeout=10) if r.status_code == 200: data = r.json() return Response(data, status=status.HTTP_200_OK) else: attempt_num += 1 # You can probably use a logger to log the error here … -
Assign ids to entries
There are following models: class Parameter (models.Model): id_parameter = models.IntegerField(primary_key=True) par_rollennr = models.IntegerField(default=0) par_definition_id = models.IntegerField(default=0) #not FK par_name = models.CharField(max_length=200) class Measurements (models.Model): id_measurement = models.AutoField(primary_key=True) par_value = models.IntegerField(default=0) line = models.ForeignKey(Line, on_delete=models.CASCADE, null=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True) parameter = models.ForeignKey(Parameter, on_delete=models.CASCADE, null=True) I write down as follows: def handle_parameters_upload(request, file): wb = openpyxl.load_workbook(file, read_only=True) first_sheet = wb.get_sheet_names()[0] ws = wb.get_sheet_by_name(first_sheet) recipe, _ = Recipe.objects.get_or_create(par_recipe=ws["B2"].value) line, _ = Line.objects.get_or_create(par_machine=ws["C2"].value) order, _ = Order.objects.get_or_create(par_fa=ws["D2"].value) parameter_data = set() measurement_data = [] for row in ws.iter_rows(row_offset=1): parameter_data.add(( row[5].value, row[6].value, row[7].value, )) # par_rollennr, par_definition_id, par_name, measurement: par_value measurement_data.append(row[8].value) # Bulk create data Measurements.objects.all().delete() Parameter.objects.all().delete() parameters = Parameter.objects.bulk_create([ Parameter( id_parameter=index, par_rollennr=p_data[0], par_definition_id=p_data[1], par_name=p_data[2], ) for index, p_data in enumerate(parameter_data) ]) Measurements.objects.bulk_create([ Measurements( line=line, order=order, recipe=recipe, par_value=m_data, parameter=parameter, ) for parameter, m_data in zip_longest(parameters, measurement_data) ]) return True Thus, I only establish connections by the first lines, by the number of parameters. How can I set the parameter_id for all records if I have them duplicated in the whole file that I process. -
Trying to save multiple files in Django 2 Admin
I have read the various posts on saving multiple files using the django 2 admin, but I still can't get it to work. My model: class Document(Model): document_id = models.AutoField(primary_key=True) document_state = models.IntegerField(choices=DOCUMENT_STATE, default=PRIVATE, verbose_name="state") documentType_id = models.ForeignKey(DocumentType, on_delete=models.CASCADE, verbose_name="document type", ) created = models.DateTimeField(auto_now_add=True, editable=False, verbose_name="date created") updated = models.DateTimeField(auto_now=True, editable=False, verbose_name="last update") storage_file_name = models.FileField('File name', upload_to=unique_file_path) thumb_storage = models.FileField(editable=False,) original_file_name = models.CharField(editable=False, max_length=200) computed_sha256 = models.CharField(editable=False, max_length=64) I create my own field in the Document admin, so I added the 'multiple' keyword to the field. The field for storage_file_name looks like this in the admin create document page: <label class="required" for="id_storage_file_name">File name:</label> <input type="file" name="storage_file_name" multiple required id="id_storage_file_name" /> I have this in save_model in the DocumentAdmin class: def save_model(self, request, obj, form, change): logger.debug("save_model START") logger.debug("obj=%s, change=%s" % (obj, change)) if (form.is_valid()): logger.debug("\tvalid form") logger.debug("form.cleaned_data=%s",form.cleaned_data) obj.metadata = form.cleaned_data['metadata'] logger.debug("files=%s" % request.FILES.getlist('storage_file_name')) files = request.FILES.getlist('storage_file_name') for f in files: logger.debug("storing file=%s" % f) obj.storage_file_name = f super().save_model(request, obj, form, change) logger.debug("save_model END") files has the right list of files I want to upload. But I can't seem to save more than the last item in the list of files. I don't get any error messages; just the …