Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Querying Relation
the code did not return all of the item's name based on employee..? how to solve this probem? did the models wrong? or the query? MODELS.PY class Employee(models.Model): name = models.CharField(max_length=100) telephone_number = models.CharField(max_length=20) address = models.TextField() email = models.EmailField() class Item(models.Model): code = models.CharField(max_length=4) name = models.CharField(max_length=100) kind = models.CharField(max_length=100) description = models.TextField() class Inventory(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('inventaris-detail', kwargs={'pk': self.pk}) VIEWS.PY how can i get all of the employee's item ? query_set = Inventory.objects.all() for query in query_set: output.append([ query.employee.name, query.item.name ]) -
How to run Django locally
Im having a hard time running Django locally when I launch the command python manage.py runserver. I keep getting a connection reset error on my browser although I occasionally manage to connect for a few seconds or minute before I get disconnected. This problem has been described elsewhere (https://github.com/Microsoft/WSL/issues/1707) although I haven’t found a solution yet. Funny thing: I have discovered I can log on via the admin site (http://127.0.0.1:8000/admin/) and as long as I stay there I have no problem. Its when I step out of admin to the site proper that the connection snaps rapidly. Im working with Django 2.2.4. Changing to localhost or using 0.0.0.0 did not help. Thoughts ? -
Where to find Openeats API description?
Good afternoon, I'm in the process to writing a client app for OpenEats (https://github.com/open-eats/OpenEats), a personal recipe & ingredients management system. Do you please know where I can find their API description? There is nothing relevant to my case here: https://openeats.readthedocs.io/en/latest/. I have of course looked at https://github.com/open-eats/openeats-api and have found noting really usable for me (I can't figure out the API entry points, but I have a weak Django background). And I have tried this as well: https://www.django-rest-framework.org/api-guide/schemas/ (which instructs about an automatic API description generation for Django) but that one gives me this error message: /usr/local/lib/python3.6/site-packages/django_filters/rest_framework/backends.py:128: UserWarning: <class 'v1.list.views.BulkGroceryItemViewSet'> is not compatible with schema generation (several warnings like that) Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() --- snip --- File "/usr/local/lib/python3.6/site-packages/rest_framework/generics.py", line 112, in get_serializer return serializer_class(*args, **kwargs) File "/code/v1/recipe/mixins.py", line 19, in __init__ fields = self.context['request'].query_params.get('fields') AttributeError: 'NoneType' object has no attribute 'query_params' Accessing the API is uneasy because of that lack of an API description, do you have any idea of where I can find some info, please? -
How can I use debugger with unit test in Python with Pycharm?
I have the following problem : I am doing some unit tests but the problem is that I cannot use the debugger I tried to click on "Debug namefile" using a breakpoint but it does not work. Alternatively, I tried to use tyhe following decorator @override_settings(DEBUG=True) but once again I had no result using this way. I precise that it is only with unit tests I have this kind of problems. The other part of the code works well. Could you help me please ? PS: to do the unit test I imported TestCase from django.test. Thank you very much ! -
Django model inheritance: is there a way to have the persons who live at a specific address?
Person is a child of Entity. Knowing that I dont figure out how to find all the persons (not entities) who live at a specific place. Address can just access to entity__xxx fields. Any idea? class Entity(BaseModel): is_physical = models.BooleanField(default=True) class EntityAddress(BaseModel): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, blank=False, null=False) address = models.ForeignKey(Address, on_delete=models.CASCADE, blank=False, null=False) class Address(BaseModel): description = models.TextField(default=None, blank=True, null=True) way = PolygonField(default=None, blank=True, null=True) class PersonManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_physical=True) class Person(Entity): objects = PersonManager() user = models.OneToOneField(User, blank=False, null=False, on_delete=models.CASCADE) -
Django password hasher using php format of function password_hash()
I have to add a backward-compatible Django application that supports legacy passwords persisted in a database created with the use of PHP function password_hash() which output is like $2y$10$puZfZbp0UGMYeUiyZjdfB.4RN9frEMy8ENpih9.jOEngy1FJWUAHy (salted blowfish crypt algorithm with 10 hashing rounds) Django supports formats with the prefixed name of the algorithm so if I use BCryptPasswordHasher as the main hasher output will be like: bcrypt$$2y$10$puZfZbp0UGMYeUiyZjdfB.4RN9frEMy8ENpih9.jOEngy1FJWUAHy I have created custom BCryptPasswordHasher like: class BCryptPasswordHasher(BasePasswordHasher): algorithm = "bcrypt_php" library = ("bcrypt", "bcrypt") rounds = 10 def salt(self): bcrypt = self._load_library() return bcrypt.gensalt(self.rounds) def encode(self, password, salt): bcrypt = self._load_library() password = password.encode() data = bcrypt.hashpw(password, salt) return f"{data.decode('ascii')}" def verify(self, incoming_password, encoded_db_password): algorithm, data = encoded_db_password.split('$', 1) assert algorithm == self.algorithm db_password_salt = data.encode('ascii') encoded_incoming_password = self.encode(incoming_password, db_password_salt) # Compare of `data` should only be done because in database we don't persist alg prefix like `bcrypt$` return constant_time_compare(data, encoded_incoming_password) def safe_summary(self, encoded): empty, algostr, work_factor, data = encoded.split('$', 3) salt, checksum = data[:22], data[22:] return OrderedDict([ ('algorithm', self.algorithm), ('work factor', work_factor), ('salt', mask_hash(salt)), ('checksum', mask_hash(checksum)), ]) def must_update(self, encoded): return False def harden_runtime(self, password, encoded): data = encoded.split('$') salt = data[:29] # Length of the salt in bcrypt. rounds = data.split('$')[2] # work factor is logarithmic, … -
403 response when making a get request
i'm getting a 403 response when making a get request to this website (https://volusia.county-taxes.com) using python3 in aws EC2 server.but i'm getting success response in my local system using same code. please help me.why im not able to make a get request in aws ec2 server? In aws EC2 server import requests requests.get('https://volusia.county-taxes.com') In my local system import requests requests.get('https://volusia.county-taxes.com') -
Django REST Framework asks for related model's id when it's already in the POST parameters
Using Django and its REST_Framework, I'm trying to add an object to my POSTGRES-11 database, whose model (Team) is related to another model (Country) by a ForeignKey relation. The JSON I send with the post request looks like this, where the number provided for country is supposed to be its id. name:"test" is_onsite:true status:"PAID" institution:"testU" country:2 But then Django return the following error: IntegrityError at /api/register/team/ null value in column "country_id" violates not-null constraint DETAIL: Failing row contains (28, , f, PENDING, , null). I've tried sending the same json with 'country' replaced with 'country_id', but I've been faced with the same error. I've already tried the solution given Here, but then Django returns this JSON instead of adding the object: { "country": [ "This field is required." ] } models.py: class Country(models.Model): name = models.CharField(max_length=255) flag = models.ImageField() class Meta: verbose_name_plural = 'Countries' def __str__(self): return self.name class Team(models.Model): name = models.CharField(max_length=255, default="", blank=True) is_onsite = models.BooleanField(default=False) status = models.CharField(max_length=50, choices=TEAM_STATUS_CHOICES, default='PENDING') institution = models.CharField(max_length=255, default="") country = models.ForeignKey(Country, on_delete=models.CASCADE, default="", blank=True) def __str__(self): return self.name serializers.py: class CountrySerializer(serializers.ModelSerializer): class Meta: model = Country fields = '__all__' class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = ['name', 'is_onsite', 'status', … -
django cron schedule don't repeat
I have hard time trying to setup django cron schedule based on guide. settings.py: INSTALLED_APPS = [ 'django_cron', ] CRON_CLASSES = [ "eventscalendar.cron.MyCronJob", ] cron.py inside eventscalendar app: from django_cron import CronJobBase, Schedule from eventscalendar.models import Subtask import random class MyCronJob(CronJobBase): frequency = 1 schedule = Schedule(run_every_mins=frequency) code = 'eventscalendar.my_cron_job' def do(self): number = random.randint(1, 100) # save data to database add_records = Subtask(subtask_name='test' + str(number), subtask_description='test' + str(number)) add_records.save() Problems: I don't see any jobs running [crontab -l] For some reason [crontab -e] on virtual server is not working - terminal output: 0 cron class is initialised once only after: python manage.py runcrons Thank you for your time. -
How to create multiple graphs based on result in Django/Flask
I am creating a web app and hope to visualize data result fetched from each result row. I am new to Flask/Django and unfortunately never used javascript before For each row of the data, there are numeric values for activity in the past several months and I would like to visualize that directly using several (k) graphs If the result has n columns, I would like to have n*k graphs in the web page. Below is what I have now in Django based on some search and I would like to have data visualization in the for loop. {% if results %} <div class="txtCentrado margenSup20 grisDC"> <h3>We found {{ count }} result{{ count|pluralize }} for your search </h3> </div> <div class="search results"> {% for resrow in results %} <div class="images"> {{ resrow.0 }} {{ resrow.1 }} {{ resrow.2 }} </div> <p></p> {% endfor %} </div> {%elif not search_term %} <h3>Insert your search here.</h3> {%elif not results %} <p>No results found.</p> {% endif %} What I tried: (Please correct me if I am wrong) Neither of HighCharts and FusionCharts is free to use. D3.js seems to need much work of javascripts that I do not have any experience with. Matplotlib need … -
Django Admin add with initial values from changelist
I have an add link to another model from a changelist view. The initial value should be taken from the changelist. Suppose: class ModelF(models.Model): name = models.CharField(max_length=20) class ModelA(models.Model): model_f = models.ForeignKey(ModelF, on_delete=models.CASCADE) field2 = .... class ModelB(models.Model): model_f = models.ForeignKey(ModelF, on_delete=models.CASCADE) field3 = .... class ModelAAdmin(admin.ModelAdmin): list_display = ['link',] def link(self, obj): return mark_safe(f"<a href={reverse('admin:app_modela_add')}>{obj.field3}</a>") I want the add link to open with default value of model_f from ModelB in add of ModelA. How to pass the the id/model_f of ModelB. Is this possible -
Django rest api - searching a method field with the search filter
im trying to filter search a rest api page and want to use a method field as one of the search fields, however when I do this I get an error stating the field is not valid and it then lists the field in my model as the only valid source serialiser: class SubnetDetailsSerializer(QueryFieldsMixin, serializers.HyperlinkedModelSerializer): subnet = serializers.SerializerMethodField() device = serializers.ReadOnlyField( source='device.hostname', ) circuit_name = serializers.ReadOnlyField( source='circuit.name', ) subnet_name = serializers.ReadOnlyField( source='subnet.description', ) safe_subnet = serializers.SerializerMethodField() def get_safe_subnet(self, obj): return '{}{}'.format(obj.subnet.subnet, obj.subnet.mask.replace('/','_')) def get_subnet(self, obj): return '{}{}'.format(obj.subnet.subnet, obj.subnet.mask) class Meta: model = DeviceCircuitSubnets fields = ('id','device_id','subnet_id','circuit_id','subnet','safe_subnet','subnet_name','device','circuit_name') views: class SubnetDetailsSet(viewsets.ReadOnlyModelViewSet): queryset = DeviceCircuitSubnets.objects.all().select_related('circuit','subnet','device') serializer_class = SubnetDetailsSerializer permission_classes = (IsAdminUser,) filter_class = DeviceCircuitSubnets filter_backends = (filters.SearchFilter,) search_fields = ( 'device__hostname', 'circuit__name', 'subnet__subnet', 'safe_subnet' ) how can include the safe_subnet in the search fields? Thanks -
how to create child page of parent class in django
I have Blockchain page and i need child page of blockchain like below in django: It can have multiple child page and how to check that this is last child page of parent class Blockchain #parent page childpage 1 childchildpage 1 and so on # child page of childpage 1 childpage 2 -
how to speed up file uploading at Django?
I have a form which sent to the server by ajax request. This form has a field for file uploading. How can to speed up file uploading? Mostly files such as images and text documents will be uploading. But there are no upload restrictions, so even large-size movies can be will be uploading. js var frm = $('#contact_form'); frm.submit(function (e) { e.preventDefault(); $.each($("div[class^='contact_form_']"), function(ind, value){ $(value).hide(); $(value).prev().css('border', 'none') }) var form_data = new FormData($('#contact_form')[0]); $.ajax({ type: frm.attr('method'), headers:{ "X-CSRFToken": $('input[name="csrfmiddlewaretoken"').val() }, url: '', data: form_data, processData: false, contentType: false, success: function(data) { console.log(data) if (data.result == 'error'){ $.each(data.response, function(key, value) { $('.contact_form_' + key).css('display', 'block') $('.contact_form_' + key).prev().css("border", 'solid #FD7900') $('.contact_form_' + key).text(value) }) } else { location.reload(); } } }); return false; }); view def post(self, request, *args, **kwargs): print(self.request.POST, self.request.FILES) contact_form = ContactFormForm(request.POST, request.FILES) if contact_form.is_valid(): contact_form.save() return JsonResponse({}) else: response = {} for k in contact_form.errors: response[k] = contact_form.errors[k][0] return JsonResponse({'response': response, 'result': 'error'}) -
Django Function Base View Search Form By Primary Key
The code sample as novice of Django, is it right practice to achieve page load per ID as shown below? View.py def testidbasesearch(request,id=None): if request.method == "GET": print ('Inside IF GET') if not id: form = MtiForiegnForm() else: instance = Mt_Issue_foriegn.objects.get(id=id) form = MtiForiegnForm(request.POST or None, instance=instance) else: print ('Inside Else GET') id=request.POST.get('pkid') instance = Mt_Issue_foriegn.objects.get(id=id) form = MtiForiegnForm(request.POST , instance=instance) return redirect(reverse('tepo1', kwargs={"id": id})) return render(request,'testingpost.html',{'form':form}) url.py path('testidbasesearch',testidbasesearch,name='testidbasesearch'), path('testidbasesearch/<int:id>',testidbasesearch,name='testidbasesearch'), testingpost.html {% extends 'base.html' %} {% block content %} <form id="postform1" method="post" action=""> {% csrf_token %} <input type="text" name="pkid" /> <input type="submit" id="submit-form" /> {% for form1 in form %} <fieldset disabled="disabled"> {{ form1 }} </fieldset> {% endfor %} </form> {% endblock %} First of all my functionality is working as expected , I just need review is it right code practice, I purposely avoid AJAX/jquery ( i.e. js) pure django /python code to load form based on id submitted. -
Navigate to Django URL from Angular
I am using Angular guard to block the pages when a user isn't logged in, the logging in is done with Django. If they're not logged in, I want them to be redirected to the Django login template. I initially had issues with Angular removing the trailing slash needed for the Django URL, this was done by adding a . after the slash I wanted to keep. This has the correct URL but it won't show the Django page unless I refresh the page, just shows my Angular 404. This is what I am using to reroute: this.router.navigate(['/accounts/login/.']); I expect the Django loging page to be shown when a user that isn't logged in tries to access any of the other pages before logging in. I am only given an Angular 404 which means the site is still accessible. -
Invalide Cursor Name
I am using Pycharm for a Django project with psycopg2 and I do some unit test. But I got a problem. Indeed, I am facing to this error : psycopg2.errors.InvalidCursorName: ERROR: the cursor « _django_curs_139677874173696_53 » does not exist Do you have any ideas to solve this problem ? I precise I am using a postgre database with pgadmin. -
Is anyone implemented django celery worker as docker container it only runs when task assigned
I am able to successfully deploy Django Celery worker as a docker container in AWS ECS service using FARGET as computing. But my concern is that celery container is running 24/7. If I can run container only when task is assigned, I can save lot of money as per AWS FARGET billing methodology. -
How to redirect in a Generic View
I am using a generic view to render my blog post item: class PostUpdateView(UpdateView, LoginRequiredMixin): model = Post # etc I have a model method on the Post model that results in a boolean True or False: @property def can_edit(self): return self.displays_set.count() == 0 If can_edit is False for the Post object, how can I refactor the view to redirect from my UpdateView to a different DetailView? -
i don't understand the error in these fie
i have facing these issue while creating template in django as i am creating template while adding template attribute in setting.py its showing the error syntax is invalid TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [[os.path.join(BASE_DIR,'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', ], }, }, ] return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "F:\myweb\myweb\settings.py", line 59 'APP_DIRS': True, ^ SyntaxError: invalid syntax MPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [[os.path.join(BASE_DIR ,'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', ], }, }, ] WSGI_APPLICATION = 'myweb.wsgi.application' i am creating a html file under ajango template but when i am trying to run it o browser it shows the error file doesnot exists from django.apps import AppConfig class NewappConfig(AppConfig): name = 'newapp' its have to show hello there!!! on browser -
A function present in views.py file need to access the images stored in my pc
I need to include some image processing code in django. For that I want to access images stored in my pc (or in static folder in django ) through function in views.py. How can I do that? -
How to make Django views require a user login?
I have a Django project with a login screen; when I enter my username and password I get directed to the home page. This works fine! But nothing is secure, I can just go to the view at /allstudyplans without logging in and see all the information there. My Question is how do I make it so it's not possible to go /allstudyplans without logging in first? Form User = get_user_model() class UserLoginForm(forms.Form): username = forms.CharField(label='', widget=forms.TextInput( attrs={ 'class': 'form-control', 'autofocus': '', 'placeholder': 'Användarnamn', } ), ) password = forms.CharField(label='', widget=forms.PasswordInput( attrs={ 'class': 'form-control mt-1', 'placeholder': 'Lösenord', } ), ) # https://docs.djangoproject.com/en/2.1/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other def clean(self): cleaned_data = super().clean() username = cleaned_data.get('username') password = cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError( 'Oh! I can\'t find that user - create user first!') elif not user.check_password(password): raise forms.ValidationError( 'Oh! That password is incorrect - try again!') elif not user.is_active: raise forms.ValidationError( 'Oh! That user is not active in the database!') Views def home(request): next = (request.GET.get('next')) form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) if next: return redirect(next) return redirect('/') context = { 'form': form, } … -
How to set a model boolean field based on conditional logic of other field values
I have a Template model with a 1:many FK with a Post model: class Template(model.Models): #foo class Post(model.Models): template = models.ForeignKey( Template, null=True, on_delete=models.SET_NULL) I want to create an 'automatic' boolean field that flags if there is one or more posts using the template (if True I will lock the template for editing). What's the best way to do this? Is it via a @property decorator on the Template model??: @property def can_edit(self): if self.object.post_set.all() >= 1: self._can_edit = True return self._can_edit else: self._can_edit = False return self._can_edit Then I would call this via {{ template.can_edit }} to display the flag status and {% if template.can_edit() %} to run conditional logic, but this does not work. -
Take the data of one table and make the field for another table
Models.py class Designation(models.Model): Name = models.CharField(max_length=50) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __str__(self): return self.Name class Meta: db_table = 'desingnation' all the data should create as field to another table -
Watching for file changes with StatReloader Exception in thread django-main-thread:
**Don't know what the problem is. I am not able to run any of my Django servers. Every time gets the same error. And don't have any idea about this. Tried reinstalling windows, python and all. But still gets same error. ** Don't know what the problem is. I am not able to run any of my Django servers. Every time gets the same error. And don't have any idea about this. Tried reinstalling windows, python and all. But still gets same error. C:\Users\JamesBond\Desktop\ONLINE WEBSITES\vishwatradelink_>manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line …