Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
API view is empty when Filtering django rest framework view by PK in urls.py
I am trying to filter my APIListView by a PK value specified in the url. The code runs however my API is empty even though i know it has data at the PKs that i am testing. Any Ideas? Models.py class Item(models.Model): Description = models.CharField(max_length=20) Price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.Description Serializers.py class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('pk', 'Description', 'Price') Views.py (API) class SingleItemAPIView(generics.ListAPIView): serializer_class = ItemSerializer def get_queryset(self): item = self.request.query_params.get('pk', None) queryset = Item.objects.filter(pk=item) return queryset Urls.py urlpatterns = [ path('<int:pk>/',SingleItemAPIView.as_view(), name='single_object_view') ] DRF Output GET /api/1/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [] -
Django Categories and Breadcrumbs Issues
Everything works normally on the admin side. However, I could not show the categories and breadcrumbs on front site. I'd appreciate it if you could help me. models.py from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Post(models.Model): title = models.CharField(max_length=120) category = TreeForeignKey('Category',null=True,blank=True) content = models.TextField('Content') slug = models.SlugField() def __str__(self): return self.title class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = (('parent', 'slug',)) verbose_name_plural = 'categories' def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = [ i.slug for i in ancestors] slugs = [] for i in range(len(ancestors)): slugs.append('/'.join(ancestors[:i+1])) return slugs def __str__(self): return self.name admin.py from mptt.admin import MPTTModelAdmin admin.site.register(Post,PostAdmin) admin.site.register(Category, DraggableMPTTAdmin) settings.py MPTT_ADMIN_LEVEL_INDENT = 20 #you can replace 20 with some other number urls.py path('category/<path:hierarchy>.+', views.show_category, name='category'), views.py def show_category(request,hierarchy= None): category_slug = hierarchy.split('/') parent = None root = Category.objects.all() for slug in category_slug[:-1]: parent = root.get(parent=parent, slug = slug) try: instance = Category.objects.get(parent=parent,slug=category_slug[-1]) except: instance = get_object_or_404(Post, slug = category_slug[-1]) return render(request, "post/detail.html", {'instance':instance}) else: return render(request, 'post/categories.html', {'instance':instance}) templates/categories.html {% extends 'base.html' %} {% load static %} {% block head_title %} {{ instance.name … -
Django customized user model.... where does user.model(...) come from?
So, I am working my way through the jungle of the django documentation in order to create an online classifieds app. Since users are supposed to be anble to post their own classifieds online, I need to make use of the user authentication system. However, they need to be able to log in by email instead of username, which is why I need to come up with a customized user model. Now, the example walk-through thats contained in the django documentation seems helpful: https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#a-full-example In order to understand django better, I am trying to go through the example line by line, and there is a point that I don't quite get: class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, ) I don't get where the "self.model(...)" comes from. Is it a method? I cannot find it in BaseUserManager... where is it defined? I don't even quite know how to phrase the question precisely because I'm so puzzled about it... could anybody just enlighten me about what we are defining here … -
How do i do a POST request in django rest framework with this model structure
i am new in django and django rest framework , i am trying to send an object with POST, but i don´t know why why it's failing, this are my models: class Region(models.Model): id_region = models.AutoField(primary_key=True) name_region = models.CharField(max_length=255) def __str__(self): return self.name_region class DataTicker(models.Model): id_data_ticker = models.AutoField(primary_key=True) ytd = models.FloatField() expense_ratio = models.FloatField() price_earnings_ratio = models.FloatField() price_book_ratio = models.FloatField() aum_ticker = models.FloatField() price = models.FloatField() nav = models.FloatField() bid_ask = models.FloatField() premiun_discount = models.FloatField() date= models.DateTimeField(auto_now=False) region_id_fk = models.ForeignKey(Region,on_delete=models.CASCADE) geography_id_fk = models.ForeignKey(Geography,on_delete=models.CASCADE) def __str__(self): return str(self.id_data_ticker) class Ticker(models.Model): id_number = models.AutoField(primary_key=True) ticker_id = models.CharField(max_length=100) index_tracked = models.CharField(max_length=255) fund = models.CharField(max_length=255) focus = models.CharField(max_length=255) inception_date= models.DateTimeField(auto_now=False) asset_id_fk = models.ForeignKey(AssetClass,on_delete=models.CASCADE) data_tickers = models.ManyToManyField(DataTicker) def __str__(self): return self.ticker_id And this are my serializers class RegionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Region fields = ('id_region','name_region','geography_id_fk') class DataTickerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = DataTicker fields = ('id_data_ticker','ytd','expense_ratio','price_earnings_ratio', 'price_book_ratio','aum_ticker','price','nav','bid_ask','premiun_discount','date','region_id_fk','geography_id_fk') region_id_fk = serializers.SerializerMethodField('get_region_id_fk') geography_id_fk = serializers.SerializerMethodField('get_geography_id_fk') def get_region_id_fk(self,obj): return obj.region_id_fk.name_region def get_geography_id_fk(self,obj): return obj.geography_id_fk.name_geography class TickerSerializer(serializers.ModelSerializer): #data_tickers = serializers.PrimaryKeyRelatedField(queryset=DataTicker.objects.all(), many=True) data_tickers = DataTickerSerializer(many=True, read_only=True) class Meta: model = Ticker fields = ('id_number','ticker_id','index_tracked','fund', 'focus','inception_date', 'asset_id_fk','data_tickers') asset_id_fk = serializers.SerializerMethodField('get_asset_id_fk') def get_asset_id_fk(self,obj): return obj.asset_id_fk.name_asset And this is the object that i am trying to send: var obj = { "ticker_id": "TEST", … -
django filter on listed jsonfield to return exact list object
We have a postgres JSONField class Demo_Model(models.Model): urls_results = JSONField(blank=True,null=True,default=dict) from mainapp.models import Demo_Model j1 = [{"name":"John","age":"15"},{"name":"cena","age":"21"}] j2 = [{"name":"Shawn","age":"9"},{"name":"Michale","age":"19"}] Demo_Model(urls_results=j1).save() Demo_Model(urls_results=j2).save() Now we have inserted our JSON data into 2 objects for Demo_Model, When we filter out the results based on keys and values of json data of urls_results field. >>> x = Demo_Model.objects.filter(urls_results__contains=[{"name":"cena"}]) >>> x <QuerySet [<Demo_Model: Demo_Model object (1)>]> >>> for eachx in x: ... print(eachx.urls_results) ... [{'age': '15', 'name': 'John'}, {'age': '21', 'name': 'cena'}] it filters based on key and value and returns the matched object. How do I filter just matched json part from the result list, instead of entire field. FROM THIS [{'age': '15', 'name': 'John'}, {'age': '21', 'name': 'cena'}] TO JUST MATCHED OBJECT PART of DICT {'age': '21', 'name': 'cena'} I know we can just run a for loop across the resultant objects to match and return. for eachx in x: for key,val in eachx.items(): if key == 'name' & val == 'cena': return eachx But it's a problem when we have a large list of urls_results, I'm looking for another way instead of looping around, what is the most effective /fast way to solve this problem? -
Django: I get `duplicate key value violates unique constraint` even if I have provided instance to ModelForm
I have a model as follows: class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) '''Basic Info''' name = models.CharField( max_length=100, verbose_name='name', null=True) alias_name = models.CharField( max_length=100, verbose_name='alias name', blank=True, null=True) last_name = models.CharField( max_length=100, verbose_name='last name', null=True) And a simple view to create or update this basic info as follows: class PersonalInfoCreateUpdateView(View): def post(self, request, *args, **kwargs): logger.info("posting a request.") instance = Person.objects.get(user=self.request.user) form = PersonalInfoForm(request.POST, request.FILES, instance=instance) # I am instantiating the form with a previous record if form.is_valid(): form.save() # Given that I have passed the instance to form, # I expect this to work but it does not. return redirect(reverse(self.post_redirect_url)) context['form'] = form return render(request, self.template_name, context=context) def get(self, request): instance, created = self.child_model.objects.get_or_create( user=self.request.user) form = PersonalInfoForm(instance=instance) context['form'] = form return render(request, self.template_name, context=context) And my form is: class PersonalInfoForm(ModelForm): class Meta: model = Person fields = ['name', 'alias_name', 'last_name'] and here's the error: Environment: Request Method: POST Request URL: http://localhost:8000/basic-info Django Version: 2.2.1 Python Version: 3.6.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_jalali', 'core', 'django_extensions'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/amir/.virtualenvs/owj/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute 84. return self.cursor.execute(sql, params) The above exception (duplicate key value violates unique constraint "core_person_user_id_key" DETAIL: Key … -
Resize image before upload django without saving
I am trying to crop and resize before uploading image, here is spinnet of my code - x,y,w,h = self.x, self.y, self.w, self.h image = Image.open(self.cleaned_data.get('profile_image')) try: for orientation in ExifTags.TAGS.keys() : if ExifTags.TAGS[orientation]=='Orientation' : break exif=dict(image._getexif().items()) if exif[orientation] == 3 : image=image.rotate(180, expand=True) elif exif[orientation] == 6 : image=image.rotate(270, expand=True) elif exif[orientation] == 8 : image=image.rotate(90, expand=True) except: pass cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((160, 160), Image.ANTIALIAS) filename = 'image' new_image = InMemoryUploadedFile(resized_image,'ImageField',\ "%s.jpg" % filename , 'image/jpeg', resized_image.__sizeof__(), None) self.cleaned_data['profile_image'] = resized_image return super(UpdateUserProfileForm, self).save() this is not working, resized image is not saved instead original get saved. I have to save it in InMemoryUploadedFile because I am using AWS S3 bucket for media files and it doesn't support absolute path for saving images. Previously in development I am using this code - x,y,w,h = self.x, self.y, self.w, self.h try: image = Image.open(update_form.profile_image) for orientation in ExifTags.TAGS.keys() : if ExifTags.TAGS[orientation]=='Orientation' : break exif=dict(image._getexif().items()) if exif[orientation] == 3 : image=image.rotate(180, expand=True) elif exif[orientation] == 6 : image=image.rotate(270, expand=True) elif exif[orientation] == 8 : image=image.rotate(90, expand=True) except: pass cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((160, 160), Image.ANTIALIAS) resized_image.save(update_form.profile_image.path) This was working fine but I need … -
Raising APIException in "update" Method of ModelSerializer does not Respond with Desired Status Code
I have a field that should not be updatable, which I've found out update method on ModelSerializer is the best to do that. What I do, pretty much, is to: def update(self, instance, validated_data): if "content" in validated_data: raise APIException( _("whatever error message is"), status.HTTP_403_FORBIDDEN, # or plain int, 403 ) return super().update(instance, validated_data) Oddly, the response's body is proper, which is: {"detail":"whatever error message is"} However, due to some unknown reason, it does not respond with status code 403, instead it responds with 500. 500 occurs when any exception is thrown during runtime in Django, yet the documentations of DRF clearly states that it especially handles APIException and responds accordingly. I do not know why it responds with 500. Environment Python 3.7.4 Django 2.2.7 Django Rest Framework 3.10.3 -
405 method not allowed while refreshing JWT Token - Django, Angular
I'm using JWT Authentication in my Django/Angular project and weird thing happens when I'm trying to get a new access token when the old one expired. I get a 405 POST METHOD NOT ALLOWED. I've set up corsheaders to allow all the methods and external hosts to access the app. The request looks fine as I'm sending the refresh token to get a new access token. What I've noticed is that it happens only on the pages which are sending POST request to django to access some data before displaying it. When I'm on a page that sends GET request or nothing, obtaining new token works perfectly good. Please take a look at the code and the responses. Error response settings.py CORS_ORIGIN_WHITELIST = ( '127.0.0.1:4200', '127.0.0.1:8082', ) CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] Handling 401 error and getting a new token in angular private handle401Error(request: HttpRequest<any>, next: HttpHandler ) : Observable<any> { if(!this.isRefreshing) { this.isRefreshing = true; this.refreshTokenSubject.next(null); return this.userService.refreshToken().pipe( switchMap((token:any) => { this.isRefreshing = false; this.refreshTokenSubject.next(token.access); return next.handle(this.addToken(request, token.access)); })); } else { return this.refreshTokenSubject.pipe( filter(token => token != null), take(1), switchMap(access … -
Choices in django
My Models: class Book(models.Model): # book types and placed BIOGRAFIA = 1 FANTASTYKA = 2 HISTORYCZNY = 3 HORROR = 4 POEZJA = 5 PRZYGODA = 6 ROMANS = 7 DRAMAT = 8 BRAK = 0 B00K_CHOICES = ( (BIOGRAFIA, 'Biografia'), (FANTASTYKA, 'Fantasy/Sci-Fi'), (HISTORYCZNY, 'Historyczny'), (HORROR, 'Horror'), (POEZJA, 'Poezja'), (PRZYGODA, 'Przygoda'), (ROMANS, 'Romans'), (DRAMAT, 'Dramat'), (BRAK, 'Brak informacji'), ) tytul = models.CharField(max_length=60, unique=True) autor = models.ForeignKey(Author, on_delete=models.CASCADE) opis = models.TextField(null=True, blank=True) gatunek = models.IntegerField(choices=B00K_CHOICES, default=BRAK) cena = models.DecimalField(max_digits=400, decimal_places=2) rok_wydania = models.DateField(null=True, blank=True) liczba_stron = models.PositiveIntegerField(null=True, blank=True) zdjecie = models.ImageField(null=False, blank=True, upload_to='zdjecia_ksiazek') przecena = models.BooleanField() def __str__(self): return self.tytul My View: def Gatunek(request, gatunek_id): ksiazki = Book.objects.filter(gatunek=gatunek_id) return render(request, 'ksiazki.html', {'ksiazki': ksiazki}) I don't think my view is too good, I don't know if it should also be {{gatunek. gatunek}} My template HTML: {% for ksiazki in ksiazki %} <div class="card" style="width: 500px"> <div class="card-body"> <img src="/media/{{ksiazki.zdjecie}}"> <div class="row"> <div class="col-sm-9"> <h2>{{ksiazki}}</h2> </div> <div class="col-sm-3"> <a href="{% url 'Edytuj_ksiazke' ksiazki.id %}"><i class="fas fa-2x fa-edit"></i></a> <a href="{% url 'Usun_ksiazke' ksiazki.id %}"><i class="fas fa-2x fa-trash-alt"></i></a> </div> </div> <p>{{ ksiazki.gatunek }} </p> <p>{{ ksiazki.opis }}</p> </div> </div> {% endfor %} It seems to me that I have a problem in Django when I … -
How to use request.path in Django View get_context_data?
I want to use last part of the url in get_context_data in the view. For example: if I have /foo/bar I want to get /bar in a variable in the view. def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx["url"] = request.path.split('/')[:-1] return ctx -
How could I query a MySQL DB to pull out all entries with an AD User's name in it while using Python/Django?
Long story short, we are running some cleanup processes on our Tableau Server environment. What I need to do is have users login to the Django page with LDAP (that's a battle for another day), then have a query run automatically that will display their workbooks in an html table. I already have the SQL DB being built, I just need to figure out how to display it to my users and how I will get it to return output in some way that flags a workbook for deletion. Any thoughts on this? PS, I am fairly new to Django and models in particular, Python not so much. -
Can I configure Django for Unit tests with restricted view on unmanaged databases?
We are a small team, trying to work with Django with a restricted access to a futurely unmanaged PostgreSQL database (i.e: only views and stored procedures ; no access to any tables) for security reasons. We tried to give (within Postgre) the user external_test the rights to create any tables inside his own schema on external, and to use the following settings (settings.py): ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'external': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgre_db', 'USER': 'external_user', 'PASSWORD': 'password', 'HOST': 'integration.project.net', 'PORT': '5432', 'TEST': { 'NAME': 'test_db', 'USER': 'external_test', 'PASSWORD': 'password', ... Using simple passing unit tests (project/app/tests/test_views.py): ... class InternalTest(TestCase): database = ['default'] def test_something(self): pass class StoredProcedureTest(TestCase): databases = ['external'] def test_one_procedure(self): with connections["external"].cursor() as cursor: cursor.callproc("some_procedure", [42, ]) pass ... If we try the first one with ./manage.py test app.tests.test_views.InternalTest → ok If we try the other one with ./manage.py test app.tests.test_views.StoredProcedureTest → circular dependency issue (ImproperlyConfigured: Circular dependency in TEST[DEPENDENCIES]) probably because it's skipping the configuration of default If we try both tests with ./manage.py test app.tests.test_views: → permission denied Creating test database for alias 'default'... Creating test database for alias 'external'... Got an error creating the test database: permission … -
Django Get Entries Separated by Month
I've got an object called entry. This object has a CharField, a DateField and a ForeignKey to a status. (The status could be "Error" or "Warning") I now want to do a page where the user can see how many entries with the status "Error" and "Warning" got created a certain number of months until today. I already got the logic that the url has a kwarg that shows the number of months. Here is what I have so far in my views.py: class graph_view(View, LoginRequiredMixin): def get(self, request, **kwargs): timeline = get_object_or_404(Timeline, id=kwargs.get('pk')) months = kwargs.get('months') The Result should look something like this: August: 5 Errors, 2 Warnings September: 4 Errors, 6 Warnings October: 0 Errors, 5 Warnings November: 2 Errors, 4 Warnings In the excample above the user selected that he wants to see the entries over the last 4 months. Does anyone have an idea how i can query these entries? Thanks for any help. -
Http Request between two dockers and nginx
I'm tryin to build and aplication made of containers with a djanjo server, a REST API an an nginx server, but I'm not able to send a post HTTP request from django to rest api. In local everythong works fine, and in the conteinari This is my request, it always get a 400 error code: headers = {'content-type': 'application/json'} r = requests.post('http://brokkr:5000/action', params=data, headers=headers) And this is my docker-compose file: version: '3.7' services: loki: build: context: ./Loki dockerfile: Dockerfile.prod command: gunicorn server.wsgi:application --bind 0.0.0.0:8000 ports: - 8000:8000 networks: - my-network depends_on: - brokkr brokkr: build: context: ./Brokkr dockerfile: Dockerfile command: gunicorn -b 0.0.0.0:5000 api:api ports: - 5000:5000 networks: - my-network nginx: build: ./nginx ports: - 80:80 networks: - my-network depends_on: - loki - brokkr networks: my-network: driver: bridge All of the containers start with out problem and both servers(django and falcon) pront that they are both listening. I think that the problem has to do with my nginx conf: upstream server{ server loki:8000; } server { listen 80; location / { proxy_pass http://server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/server/web/staticfiles/; } } -
Django: ImportError cannot import name Comment
Environment: Request Method: GET Django Version: 1.8.5 Python Version: 2.7.12 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'home', 'payment', 'newsletter', 'orderApp', 'log', 'rest_framework', 'rest_framework.authtoken', 'corsheaders') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware') Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 119. resolver_match = resolver.resolve(request.path_info) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve 367. sub_match = pattern.resolve(new_path) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve 239. return ResolverMatch(self.callback, args, kwargs, self.name) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in callback 246. self._callback = get_callable(self._callback_str) File "/usr/local/lib/python2.7/dist-packages/django/utils/lru_cache.py" in wrapper 101. result = user_function(*args, **kwds) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in get_callable 105. mod = import_module(mod_name) File "/usr/lib/python2.7/importlib/init.py" in import_module 37. import(name) File "/var/newsletter/views.py" in 30. from .models import Comment Exception Type: ImportError at /frequently-asked-questions/ Exception Value: cannot import name Comment -
What is the equivalent of this query in Django Filter
What is the equivalent of this query in Django Filter I need to get email address of the people having birthday today. select email from lp7ms_coworker_data where Extract(month from dob)=EXTRACT(month FROM CURRENT_DATE) and Extract(day from dob)=EXTRACT(day FROM CURRENT_DATE) -
How did a hacker produce this GET request?
I am just about to go live with a website and am addressing security issues. The site has been public for some time but not linked to the search engines. I log all incoming requests and today noticed this one: GET /home/XXXXX/code/repositories/YYYYY-website/templates where XXXXX is a sudo user on my server and YYYYY is my company name. This is actually the structure of my Django project code. My website is coded using Django and runs under Apache2 on Ubuntu. My question is how can this guy possibly know the underlying code/directory structure on my server, in order to create this request? Their IP is : 66.249.65.221. They come up as 100% a hacker on https://ip-46.com Any contributions welcome. -
Configure Apache for Django REST backend and React frontend on same domain
How to configure Apache for Django REST backend and React frontend on same domain One domain (for solve crossdomain problems). Urls: example.com/ example.com/api/ where: example.com/ - React-based frontend example.com/api/ - Django-based REST backend How implement it with Apache ? I think some like a: <VirtualHost *:80> ServerName ${DOMAIN} DocumentRoot ${SITE_FOLDER} CustomLog /var/log/apache2/${DOMAIN}_access.log common ErrorLog /var/log/apache2/${DOMAIN}_error.log WSGIDaemonProcess ${DOMAIN} user=${APACHE_USER} group=${APACHE_GROUP} python-path=${SITE_FOLDER}:${VENV_PACKAGES_PATH} WSGIProcessGroup ${DOMAIN} WSGIScriptAlias / ${SITE_FOLDER}/core/wsgi.py Alias /static/ ${SITE_FOLDER}/static/ <Directory ${SITE_FOLDER}/static> Require all granted </Directory> <Directory ${SITE_FOLDER}/core> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> is the backend, it serve /api ...but, how to implement frontend ? -
How to upload multiple images with one value in Django
i'm trying to upload multiple images with one value(e.g image_id is 1 and number of images are 5, images_id is 1 it holds 5 images). How to do this. upload.html <form action="#" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="image_id" placeholder="Image Id"> <input type="file" name="file" multiple> <button type="submit"> Upload </button> </form> views.py def multi_image(request): if request.method == 'POST': img_id = request.POST.get('image_id') file = request.FILES.getlist('file') data_save = Res(image_id = img_id ) data_save.save() filter_data = Res.objects.filter(image_id= img_id) if len(filter_data) > 0: for i in file: print(i) Res.objects.create(image= i) return render(request, 'upload.html', {}) models.py class Res(models.Model): image_id= models.CharField(max_length=10, blank=True, null=True) image = models.FileField(upload_to='images', blank=True, null=True) forms.py class FileForm(forms.Form): class Meta: model = Res fields = '__all__' -
Add button in django admin site
how to put button like in the picture? and it will link in my html? this is my admin.py @admin.register(gradingPeriodsSetting) class gradingPeriodsSettingAdmin(admin.ModelAdmin): list_display = ('School_Year', 'Education_Levels', 'Courses', 'NumberOfGradingPeriods', 'Status') ordering = ('pk',) models.py class gradingPeriodsSetting(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) NumberOfGradingPeriods = models.IntegerField(blank=True, null=True) -
Can I display the SerializerMethodField in Django admin
I am creating a custom field in my serializers file new_field= serializers.SerializerMethodField(read_only=True) def get_new_field(self,obj): # do something Is there a way I can display this field in the django admin panel? -
Extract values from object in django
I'm looking to extract the '35' and '34' values from this object: [<FriendshipRequest: 35>, <FriendshipRequest: 34>] These are primary keys which i would like to use as parameters to get information about the specific user the primary key relates to but I am unsure on how to separate the values from the rest of the object attributes to substitute into User.objects.get(pk=pk) as at the moment pk=<FriendshipRequest: 35> whereas i'd like pk=35. I am just wondering if anyone has any ideas on how to approach this problem? Cheers -
How do I retrieve data from field that is in a class meta(object)
I have a class in a models.py file : class classname(models.Model): and within this class is class meta (object) examplefield I am trying to retrieve data from a field that is within this class meta object via the following command: classname._meta.get_field('examplefield') Instead of getting the actual all the data within this field I keep getting the type: <django.db.models.fields.FloatField: examplefield> How can I retrieve the actual data and print to screen? -
Is there any method to query mongo db views with pymongo or mongoengine?
I want generate a user Report. For that I have created a view by combining data from two collections. Now I want to query this view and fetch data, is there any method to do this by pymongo or mongoengine. My application is written with django.