Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Open the url with Access Token which comes in API response
I have a set of api calls which can be accessible by Access Token and I'm able to get responses from the apis but one of the responses contain URL but when I try to access it, url asks for Log in which i'm already Logged in because thats how I got Access Token. API response: { "root": "some value", "blocks": { "some value": { "display_name": "some display name", "block_id": "abc123", "view_url": "https://www.abc.come", "web_url": "https://www.abv.com", "type": "some type", "id": "some id" } } } So from this response I want to access "web_url" so when i do a Get request, it asks for Log in. So how can I access web_url without Log in ? -
Acessing dynamic url in post method
in views.py class ProcessMessage(TemplateView): template_name = 'chatbot/chat.html' def get_object(self): id=self.kwargs.get('pk') obj=None if id is not None: obj= User.objects.get(pk=id) return obj def get(self, request, pk=None,*args, **kwargs): obj=self.get_object() print(obj,pk) super(ProcessMessage, self).get(request, *args, **kwargs) return render(request, self.template_name, {'form': ChatForm()}) def post(self, request, pk=None,*args, **kwargs): obj=self.get_object() pk=pk print(pk) print('obj is',obj) form = ChatForm(data=request.POST) # log = logging.basicConfig(level=logging.DEBUG) # print('post from index') if form.is_valid(): //////something//// in urls.py app_name = 'chatbot' urlpatterns = [ path('demo', views.ProcessMessage.as_view(), name='index'), path('<uuid:pk>/demo', views.ProcessMessage.as_view(), name='index'), ] I am getting the value of obj and pk inside get method but I want those value inside post method also(getting value None currently) I need id/pk from URL in def Post method to get user information(no I don't want to use request.user) -
Save and read file in django media folder from views
I have a function in my django views which create barcode and saves it in the os temporarily. How can I save and read it in the Media Folder?? Settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Views.py for i in items: barcode = get_barcode(value=i, width=600) a = barcode.save(formats=['PNG'], fnRoot='R123') #save this in Media folder print("a ",a) with open(a, 'rb') as image: #read from the Media folder img = image.read() grf = GRF.from_image(img, str(i)) grf.optimise_barcodes() print(grf.to_zpl()) -
creating dynamic dependent drop down from database in django
i have two drop downs from the mysql database in which both are interdependent. what i need is when i select an area from the first drop down, the second drop down as to filter accordingly matching the area from the first drop down. can anyone help me out. [The first drop down is area and the second drop down is zone ]. -
How to deploy a Django application with react serving from its static files on aws elastic beanstalk?
i have deployed a django project on aws beanstalk, gave static files path from aws elasticbeanstalk console still app is not showing up. instead i am getting this error error Failed to load resource: the server responded with a status of 404 (Not Found) -
How to use middleware for specific call in djnago web app?
I want to use middle ware in my django web app . But the problem is that i want to use middle ware only after user successfully login. I declare my custom middle ware in setting.py file but it's gives error because custom middle ware is called at unnecessary restful call. How do i call middle ware while some specific restful call. -
How to make "Shortcodes" for Django like in WordPress?
Most of my web dev stuff has been with WordPress, but I'm transitioning to Django now. So far, I'm getting the hang of it. However, one thing WordPress has that Django doesn't seem to is Shortcodes. And I desperately need them on my Django site. The way it works on my old WP site is like this: "[equipment]Grappling Hook[/equipment]". A user would type that into a TextField, somewhere within the rest of their content, and then it's displayed on the page (like in say a comment or a forum post) and it's automatically turned into a hyperlink with data that comes from a database query using "Grappling Hook" as the name to query for. Basically, [equipment]Grappling Hook[/equipment] written within a TextField automatically turns into: <a class="tooltip" href="/equipment/grappling-hook">Grappling Hook</a> when rendered on the actual page. I have scoured all of Google looking for a solution to achieve this same functionality with Django, but I just can't figure it out. I found an old app called django-shortcodes but there's very little documentation, it only seems to have a YouTube shortcode and I have no idea how to add custom ones. It doesn't have to work exactly like WordPress, either. I just need … -
Creating a User and Role Management System with multiple hierarchies
A company is divided into multiple branches. The company has 1-2 super admins who have access to everything. A branch is a separate physical location and operates as a separate business entity. A branch can have multiple departments. A department has a specific function. For example, a department will be defined as a knitting, weaving, dyeing, garmenting department. List of departments can be thought of as static as they will only be updated when developers create a new module. So I can end up having one branch that has a knitting and weaving department and another branch which has a knitting and a dyeing department. The same department should have fairly common roles throughout the different branches of a company. A person should only have access to rights of the branch that they have been given access to. When it comes to the UI/ performing actions, there is no point in showing all the screens for all the departments as screens can be department specific. So, if the screen belongs to a particular department and one has access to it, will they be able to see and modify it. Additionally, a user can be the Admin (having all the access) … -
Make change_list column editable AND change its name without changing the Model class field label
I am new to Django and am facing some issues with customizing a change_list. I am trying to make a changelist column editable, AND change the column's display name. I managed to change the display name of the column by using a callable that returns the model field value, setting its short_description property to the new column name and then adding the callable to the list_display, which works fine. I then add the callable to the list_editable, but then the editable field cannot get resolved. I get the error The value of 'list_editable[6]' refers to 'get_instruction_date', which is not an attribute of 'employee.Onboarding'. Is there a way to get this working (make column editable AND changing its display name/label) without having to change the Model itself? -
Is there is any way I can make filtering inside models in Django?
I create custom Account model and I add view columns like is_student, is_teacher. So I make another class in another app so how can I do filter something like this in models. from accounts.models import Account a = Account.objects.filter(is_student=True) class Table(models.Model): student = models.ManyToManyField(a, on_delete=models.CASCADE) -
How to list the names of the objects in a PostGreSQL database tables in a Django Application running on Google Cloud App Engine
I have a Django Application running on Google Cloud App Engine. How can I list all the names of the object models / tables in the PostGreSQL database ? -
datepicker modification for form filling
I want to make sure that the dates that are displayed in the datepicker lie between the job start and end dates. However i am not able to add the correct js code for the same. can someone please help me with this? I have written the js code modification i tried, however the change is not reflected in the application. I tried with writing minDate : 0 as well, but no change was seen. $(document).ready(function() { $("#datepicker").datepicker({ minDate : 'job.start_date' }); }); -
Inherited model with FK to base model overwrites base reference
I have a situation where I have 2 models, with the second model (B) being a subclass of the first (A), and also having a (different) FK reference to another instance of same parent model (A). The objective is to have some special cases of A linked to other instances of A's in a new table, B's. For reasons I won't get into here, these need to be 2 different models (ie I can't add a nullable 1-to-1 reference field on A). This is illustrated below. class A(models.Model): name = models.CharField() class B(A): reference = models.ForeignKey(A) However now when I try instantiate B with a reference to a different A, it doesn't work. Consider the following: >>> a1 = A(name='a1') >>> a1.save() >>> b1 = B(name='b1', reference=a1) >>> b1.save() >>> b1.id 1 >>> b1.reference.id 1 Or alternatively: >>> a1 = A(name='a1') >>> a1.save() >>> b1 = B(name='b1') >>> b1.save() >>> b1.reference = a1 >>> b1.save() >>> b1.id 2 >>> b1.reference.id 2 Whereas what I would like here is for b1.id to equal 2 and b1.reference.id to equal 1 (referencing a1). What is going on here? Why can't I have independent references to the base instance with the ptr_id and a … -
Django Rest-Framework, I'm facing problem with viewsets and routers
I have been trying to implement Default Viewsets and router but I'm getting this error ModuleNotFoundError: No module named 'router'. Do I have to add anything to the installed apps for that? My code is as follows. views.py------- from rest_framework import viewsets from rest_framework.response import Response from rest_framework import status from django.shortcuts import get_object_or_404 from .models import example from .serializers import exampleSerializer class exampleviewset(viewsets.ViewSet): def list(self, request): ex=example.objects.all() serializer=exampleSerializer(ex, many=True) return Response(serializer.data) def create(self, request): serializer=exampleSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def retrieve(self, request, pk=None): queryset=example.objects.all() ex=get_object_or_404(queryset, pk=pk) serializer=exampleSerializer(ex) return Response(serializer.data) urls.py------ from django.urls import path, include from .views import exampleviewset from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'home/', exampleviewset, basename='view_set') urlpatterns = [ path('viewset/', include('router.urls')) ] -
Django IntegrityError at / NOT NULL constraint failed: myapp_paitents.father_id
I am creating a fairly simple app in Django where 3 models are there Paitents,Father and Mother i am assigning foreignkey of father mother in paitents model, Intention is to get paitent detail including parent's details and save it to database but i am getting IntegrityError at / NOT NULL constraint failed: myapp_paitents.father_id I tried to search in same issue but i did't got one. Please someone help me with that. models.py file from django.db import models class Father(models.Model): f_name = models.CharField(null=True, max_length=20) f_age = models.IntegerField(null=True) f_occupation = models.CharField(null=True, max_length=20) f_edu = models.CharField(null=True, max_length=20) f_income = models.FloatField(null=True) def __str__(self): return self.f_name class Mother(models.Model): m_name = models.CharField(null=True, max_length=20) m_age = models.IntegerField(null=True) m_occupation = models.CharField(null=True, max_length=20) m_edu = models.CharField(null=True, max_length=20) m_income = models.FloatField(null=True) def __str__(self): return self.m_name class Paitents(models.Model): p_name = models.CharField(null=True, max_length=20) p_age = models.IntegerField(null=True) p_edu = models.CharField(null=True, max_length=20) p_add_com = models.CharField(null=True, max_length=200) p_add = models.CharField(null=True, max_length=200) father = models.ForeignKey(Father, on_delete=models.CASCADE) mother = models.ForeignKey(Mother, on_delete=models.CASCADE) def __str__(self): return self.p_name views.py from django.shortcuts import render from .models import * def index(request): if request.method == 'POST': paitent = Paitents() fathers = Father() mothers = Mother() fathers.f_name = request.POST.get('f_name') fathers.f_age = request.POST.get('f_age') fathers.f_occupation = request.POST.get('f_occupation') fathers.f_edu = request.POST.get('f_edu') fathers.f_income = request.POST.get('f_income') mothers.m_name = request.POST.get('m_name') … -
Django/xhtml2pdf - module 'types' has no attribute 'resolve_bases'
When I run the following code I get module 'types' has no attribute 'resolve_bases' a pdf file is saved but it is empty def render_pdf_view(request): file = 'my_file.pdf' resultFile = open(file, "w+b") sourceHtml = 'test' pisaStatus = pisa.CreatePDF( sourceHtml, # the HTML to convert dest=resultFile) -
return id if get_or_created inserts data, django
maybe it's simple question to ask but couldn't figure out how. I am inserting data with get_or_created and if there is a insert then trying to return that row's ID. To achieve this I tried like it below. obj, created = Advertisements.objects.get_or_create(budgets_id=pid, ad_brand=ad_brand, ad_kind=ad_kind, saved_date=today) print(created.id) even if there is an insert. it returns an error. what is the right way to get an ID in this kind of situation. 'bool' object has no attribute 'id' -
How to print model fileds as json output
views.py def districts_list(request): obj_districts_list = Districts.objects.all() data = serializers.serialize( 'json', obj_districts_list, fields=('district_name')) return HttpResponse(data, content_type="application/json") models.py class Districts(models.Model): id = models.AutoField(primary_key=True) district_name = models.CharField(max_length=40) country = models.ForeignKey('Country', on_delete=models.CASCADE) state = models.ForeignKey('States', on_delete=models.CASCADE) def __str__(self): return '{}'.format(self.district_name) OUTPUT: Output is JSON format But i just want the fields inside the Accounts.districts as output in JSON format. Thank You in advance.. HAVE A NICE DAY.. -
Django: duplication check failed
I currently develop a Django project that is currently test by a colleague One of my edit form have a validation check on duplicate (cf def clean method in forms.py) that is the combo of 3 fields: asp_ent_loc / med_num / asp_ent_dat but even with this control on form validation, my colleague managed to registered 2 records with the same combo (PA / AAB / 2020-03-16) the problem is that I did not manage to reproduce this bug... models.py: class Entree(models.Model): asp_ent_cle = models.AutoField(primary_key=True) asp_ent_loc = models.CharField("Site concerned by the operation", max_length=10, null=True, blank=True) med_num = models.CharField("Trial batch number", max_length=3, null=True, blank=True,) asp_ent_dat = models.DateField("Entry date", null=True, blank=True) asp_ent_pro_pay = models.CharField("Country of treatment origin in case of entry", max_length=10, null=True, blank=True) asp_ent_pro_sit = models.CharField("Processing source site in case of entry", max_length=10, null=True, blank=True) opr_nom = models.CharField("Input operator", max_length=10, null=True, blank=True) opr_dat = models.DateField("Entry date", null=True, blank=True) log = HistoricalRecords() class Meta: db_table = 'pha_asp_ent' verbose_name_plural = 'Entries' ordering = ['asp_ent_cle'] permissions = [ ('can_manage_drugs','Can manage trial drugs'), ] forms.py class EditForm(forms.ModelForm): # surcharge méthode constructeur (__init__) pour avoir accès aux variables de sessions # https://stackoverflow.com/questions/3778148/django-form-validation-including-the-use-of-session-data def __init__(self, request, *args, **kwargs): super(EditForm, self).__init__(*args, **kwargs) self.request = request self.language = request.session.get('language') self.user … -
Django Dropdown & Field Representation
I've got the following Situation, I have a rather large legacy model (which works nonetheless well) and need one of its fields as a distinct dropdown for one of my forms: Legacy Table: class SummaryView(models.Model): ... Period = models.CharField(db_column='Period', max_length=10, blank=True, null=True) ... def __str__(self): return self.Period class Meta: managed = False # Created from a view. Don't remove. db_table = 'MC_AUT_SummaryView' Internal Model: class BillCycle(models.Model): ... Name = models.CharField(max_length=100, verbose_name='Name') Period = models.CharField(max_length=10, null=True, blank=True) Version = models.FloatField(verbose_name='Version', default=1.0) Type = models.CharField(max_length=100, verbose_name='Type', choices=billcycle_type_choices) Association = models.ForeignKey(BillCycleAssociation, on_delete=models.DO_NOTHING) ... def __str__(self): return self.Name Since I don't want to connect them via a Foreign Key (as the SummaryView is not managed by Django) I tried a solution which I already used quite a few times. In my forms I create a ModelChoiceField which points to my Legacy Model: class BillcycleModelForm(forms.ModelForm): period_tmp = forms.ModelChoiceField(queryset=SummaryView.objects.values_list('Period', flat=True).distinct(), required=False, label='Period') .... class Meta: model = BillCycle fields = ['Name', 'Type', 'Association', 'period_tmp'] And in my view I try to over-write the Period Field from my internal Model with users form input: def billcycle_create(request, template_name='XXX'): form = BillcycleModelForm(request.POST or None) data = request.POST.copy() username = request.user print("Data:") print(data) if form.is_valid(): initial_obj = form.save(commit=False) initial_obj.ModifiedBy = … -
Creating Django's blog post scheduler [closed]
so I am making a Django blog web app and I was just wondering if it is possible for one to schedule when the blog posts should be posted and if it's possible, how would I go about it? I have tried googling out the solution but the only answer I've gotten so far was one related to scheduling tasks periodically. Any solution would be greatly appreciated. -
DRF: how to call post method once the put method has been successfully implemented
I have two separate methods: to load and validate a csv file FileUploadView(APIView) [PUT] to add new objects to the database based on their uploaded file data CsvToDatabase [POST] For this purpose, 2 different url addresses are used Now I want to combine this functionality into one, so that the file is loaded with processing and creation of instances in the database is done on a single request. That is, the final goal - the application user sends the file to the server and then everything happens automatically. file upload class FileUploadView(APIView): parser_classes = (MultiPartParser, FormParser) # renderer_classes = [JSONRenderer] permission_classes = (permissions.AllowAny,) serializer_class = VendorsCsvSerializer def put(self, request, format=None): if 'file' not in request.data: raise ParseError("Empty content") f = request.data['file'] filename = f.name if filename.endswith('.csv'): file = default_storage.save(filename, f) r = csv_file_parser(file) status = 204 print(json.dumps(r)) else: status = 406 r = "File format error" return Response(r, status=status) create instances class CsvToDatabase(APIView): permission_classes = (permissions.AllowAny,) serializer_class = VendorsCsvSerializer def post(self, request, format=None): r_data = request.data ... #some logic ... serializer = VendorsCsvSerializer(data=data) try: serializer.is_valid(raise_exception=True) serializer.save() except ValidationError: return Response({"errors": (serializer.errors,)}, status=status.HTTP_400_BAD_REQUEST) else: return Response(request.data, status=status.HTTP_200_OK) how can I correctly combine two methods in one endpoint so that if csv … -
Direct assignment to the forward side of a many-to-many set is prohibited. Use interested_time.set() instead
I'm trying to implement multiple singup form with django all auth. It is working fine for the first form because first form doesn't contain any type of many to many relationship. In case of second form it contains lots of many to many realtion ship. I'm new to django and allauth, I didn't know how to handle this problem. some of the code snippets is given below. models.py class JobSeekerProfile(models.Model): user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE) full_name = models.CharField(max_length=255) religion = models.ForeignKey(Religion, on_delete=models.CASCADE) interested_area = models.ManyToManyField(ServiceArea) interested_time = models.ManyToManyField(WorkingShift) forms.py class JobSeekerSignupForm(SignupForm): full_name = forms.CharField( .......... ) interested_area = forms.MultipleChoiceField( required=True, error_messages={'info': 'Interested Area is required'}, label="Interested Area", choices=[[0, '']] + [[r.id, r.title] for r in ServiceArea.objects.all()], widget=forms.SelectMultiple(attrs={ 'id': "inputGroup1_17", 'class': select_input_class, 'style': "width: 100%;", 'data-placeholder': "Interested Area ", 'data-open-icon': "fa fa-caret-down", 'data-close-icon': "fa fa-caret-up", }), ) ........ def save(self, request): user = super(JobSeekerSignupForm, self).save(request) user.is_job_seeker = True job_seeker = JobSeekerProfile( user=user, full_name=self.cleaned_data.get('full_name'), interested_area_set=self.cleaned_data.get('interested_area'), ........ interested_time=self.cleaned_data.get('interested_time'), ) user.save() job_seeker.save() return user and views.py class JobSeekSignupView(SignupView): template_name = 'user/job-seeker-signup.html' form_class = JobSeekerSignupForm redirect_field_name = 'next' view_name = 'jobseekersignup' success_url = None def get_context_data(self, **kwargs): ret = super(JobSeekSignupView, self).get_context_data(**kwargs) ret.update(self.kwargs) return ret -
Could not find the GDAL library (tried "gdal203", "gdal202", "gdal201", "gdal20", "gdal111"). Is GDAL installed?
i'm trying to make location based web application with django and sub framework (geodjango) and postgresql - postgis , windows 10 i've also installed GDAL through GDAL-2.4.1-cp37-cp37m-win_amd64.whl,geos, and added this line to settings.py file GDAL_DATA = 'C://<path_to_your>/venv/Lib/site-packages/osgeo/data/gdal' GDAL_LIB = 'C://<path_to_your>/venv/Lib/site-packages/osgeo' and database DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': '...', 'USER':'....', 'HOST':'localhost', 'PASSWORD':'....', 'PORT':'5432', } } but still getting this error django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal203", "gdal202", "gdal201", "gdal20", "gdal111"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. -
django rest framework copy password to extra fields in the user table
I have a project that needs to read the password for other connection operations. So I need to be able to read the plaintext password from the database. But the password in the database is encrypted with md5 and cannot be decrypted. So I want to save a copy of the password when I register as a user/super admin, not in plain text, but encrypted by a encryption and decryption algorithm, so I can decrypt it and get the password when I need it UserModel is as follows: class User(AbstractUser): jwt_secret = models.UUIDField(default=uuid.uuid4) test= models.CharField(max_length=200, null=False) def __str__(self): return self.username method one modify UserSerializer create function class UserSerializer(serializers.ModelSerializer): def create(self,validated_data): user = User.objects.create( username=validated_data['username'], test=encry(validated_data['password']) ) user.set_password(validated_data['password']) user.save() return user This can indeed be done when registering a user, when using http://hostname:port/docs/swagger/ test registration. But, when using the python3 manage.py createsuperuser command, the test field cannot be inserted, which is shown as empty. Method two So I tried using Manager Refer to the following Customizing authentication in Django¶ MyUserManager is as follows: class MyUserManager(UserManager): def create_user(self, username, email=None, password=None, **extra_fields): extra_fields.setdefault('test', encry(password)) return self._create_user(username, email, password, **extra_fields) def create_superuser(self, username, email, password, **extra_fields): extra_fields.setdefault('test', encry(password)) return self._create_user(username, email, password, **extra_fields) …