Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Command "python setup.py egg_info" failed with error code 1 when trying to install unirest
I got this error after running the command pip install unirest to use the unirest in my views.py. I am trying to use the api of petrol price in my project in which run this command (geo) ABHISHEKs-MacBook-Air:map abksharma$ pip install unirest Collecting unirest Using cached https://files.pythonhosted.org/packages/92/da/2149cbd7a8c78f8b76b377379c1bda64ec36cc13315d55f6f7de6d094ac5/Unirest-1.1.7.tar.gz Collecting poster>=0.8.1 (from unirest) Using cached https://files.pythonhosted.org/packages/9f/dc/0683a458d21c3d561ab2f71b4fcdd812bf04e55c54e560b0854cea95610e/poster-0.8.1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/84/0bcm7b0s6kx3496xf5ply6wh0000gn/T/pip-install-vf9ffv_s/poster/setup.py", line 2, in <module> import poster File "/private/var/folders/84/0bcm7b0s6kx3496xf5ply6wh0000gn/T/pip-install-vf9ffv_s/poster/poster/__init__.py", line 29, in <module> import poster.streaminghttp File "/private/var/folders/84/0bcm7b0s6kx3496xf5ply6wh0000gn/T/pip-install-vf9ffv_s/poster/poster/streaminghttp.py", line 61 print "send:", repr(value) ^ SyntaxError: invalid syntax ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/84/0bcm7b0s6kx3496xf5ply6wh0000gn/T/pip- install-vf9ffv_s/poster/ views.py from django.shortcuts import render import requests import unirest def petrol(request): response = unirest.post("https://fuelprice.p.mashape.com/", headers={ "X-Mashape-Key": "eqPyWAd3Wrmsh52b6fvG3AQ5T2ygp1KZhDfjsng702Sd7DmWN7", "Content-Type": "application/json", "Accept": "application/json" }, params=("{\"fuel\":\"p\",\"state\":\"dl\"}") ) price = response.json() return render(request, 'petrol/petrol.html', {'price':price}) url.py from django.urls import path from .import views urlpatterns = [ path('', views.petrol, name='petrol') ] -
What is meant by lightweight server in python django
I was reading django basics document from tutorials point , i came across term " lightweight server ". What does lightweight mean? -
Django Migration: Not reflecting changes | creates only id
I´m stuck trying to migrate my new models using django 2.1. For some reason it only creates the id column. Having done that, I get the following strange behaviour: makemigrations ui: No changes detected in app 'ui' migrate ui No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Doing as said by the cli I´m ending up in a loop. Here is my models.py from django.db import models from django.contrib.auth.models import User class Costumer(models.Model): costumer_id: models.AutoField(primary_key=True) costumer_su_object: models.ForeignKey(User, on_delete=models.CASCADE) set_costumer_mails: models.BooleanField(default='1') set_contact_point: models.EmailField(blank=True) set_tracking_link: models.CharField(max_length=100, blank=True) set_primary_color: models.CharField(max_length=100, blank=True) set_warn: models.IntegerField(max_length=2) stat_saved: models.IntegerField(max_length=100, blank=True) stat_active: models.IntegerField(max_length=100, blank=True) stat_warn: models.IntegerField(max_length=100, blank=True) stat_case: models.IntegerField(max_length=100, blank=True) I do not get any error messages. As well I already deleted the table and all migrations and tried to do an initial migration from scratch (with all the above set). It again creates the id column and that is it. My 0001_initial.py looks like this: # Generated by Django 2.1.2 on 2018-11-25 16:55 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = … -
How to use django default permission in class based view
Django has nice built in admin permission setup. Want to use add, change, delete, view permission in class based generic view outside of the admin panel. How to do this? -
Error while creating superuser in Django web-app
In the project I'm working on is a teacher-student exam app. For the login page, the user is an extension of AbstractUser which contains details of both teacher and student. This is models.py in my app named user: from django.db import models from django.contrib.auth.models import AbstractUser class Courses(models.Model): course_id = models.CharField(max_length=200) department = models.CharField(max_length=200) def __str__(self): return self.course_id class User(AbstractUser): is_student = models.BooleanField(default=True) is_instructor = models.BooleanField(default=False) department = models.CharField(max_length=200) course = models.ForeignKey(Courses, on_delete=models.CASCADE, null=True) def __str__(self): return self.username When I try to create a superuser, I get this long error after entering the username, email id, password twice. What's wrong? (venv) praneeth@My-MBA:~/Desktop/New_E/eeeee$ python manage.py createsuperuser Username: superuser Email address: jkl@j.com Password: Password (again): This password is too common. Bypass password validation and create user anyway? [y/N]: n Password: Password (again): Traceback (most recent call last): File "/Users/edubillipraneeth/Desktop/New_E/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/edubillipraneeth/Desktop/New_E/venv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 296, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: user_user.course_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/edubillipraneeth/Desktop/New_E/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/edubillipraneeth/Desktop/New_E/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/edubillipraneeth/Desktop/New_E/venv/lib/python3.7/site-packages/django/core/management/base.py", line … -
Django - How to set up ModelViewset with Serializer API endpoint to update if object exists else create?
I am quite confused with how to use ModelViews and Serializers in creating an API using Django Rest Framework. What I am trying to do is this: I have a "Rating" and "Product" model, and I want to figure out how to set up my ModelViewSet, Serializer, and React component such that when I call a function in that React component, I want to: (1) Check to see if the Rating for the Product exists for the current User, and if it exists, then update the rating. (2) If the Rating does not exist, create a new rating In my models.py: class Product(models.Model): name = models.CharField(max_length=100) ... def __str__(self): return self.name class Rating(models.Model): rating = models.IntegerField() product = models.ForeignKey('Product', related_name='ratings') def __str__(self): return "{}".format(self.rating) In my views.py: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer class RatingViewSet(viewsets.ModelViewSet): queryset = Rating.objects.all() serializer_class = RatingSerializer In my serializers.py: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('pk', 'name', 'description', ...) class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ('pk', 'rating', 'user', 'product', ...) In my urls.py: from rest_framework import routers router = routers.DefaultRouter() router.register(r'products', views.ProductViewSet) router.register(r'ratings', views.RatingViewSet) In my React component, I have the below function: const createRating = (rating, … -
Django - Displaying model having content type in admin panel
I am new to Django and I am facing a problem. I have multiple model that require address and phone number against address. And only phone number can be associated with some of models. So, I have made polymorphic relation for "Addresses" and "PhoneNumber". Like here: class PhoneNumber(SoftDeleteModel): phone_number = PhoneNumberField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.phone_number.as_e164 class Address(SoftDeleteModel): house_number = models.CharField(max_length=255) street_number = models.CharField(max_length=255) area = models.CharField(max_length=255) city = models.CharField(max_length=255) country = models.CharField(max_length=255) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() phone_number = GenericRelation(PhoneNumber) content_object = GenericForeignKey('content_type', 'object_id') created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return str(self.house_number)+", "+str(self.street_number)+", "+self.area+", "+self.city+", "+self.country These are the model for Address & PhoneNumber I am using Address model in Vendor like: class Vendor(SoftDeleteModel): vendor_name = models.CharField(max_length=500) vendor_phone = GenericRelation(PhoneNumber) vendor_address_detailed = GenericRelation(Address) vendor_contact_person = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.vendor_name When I am making crud in admin for vendor I am able to get only Addresses not PhoneNumber in Address model like in in this … -
How to insert character varying array into postgresql
I want to insert a json array into postgresql?This is my code: def get(self,request): request_data = ''' { "name":"a", "isbn":"dd", "author":["a","b"], "publisher":["a","b"], "price":"ddd"} ''' data = json.loads(request_data) serializer = BookSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) And this is my field define: class BookSerializer(serializers.Serializer): name = serializers.CharField(required=False, allow_blank=True, max_length=100) isbn = serializers.CharField(required=False, allow_blank=True, max_length=100) author = serializers.ListField(required=False) publisher = serializers.ListField(required=False, max_length=100) price = serializers.CharField(required=False, allow_blank=True, max_length=100) When i am request the function,it throws error: "[" must introduce explicitly-specified array dimensions How to avoid this problem? -
DJANGO:How to perform AND operation for my query?
There are two models .I want to make query to extract only the app exact app related Adspaces . models.py class Appname(models.Model): user=models.ForeignKey(User,related_name='appname', null=True, default=None,on_delete=models.CASCADE) name=models.CharField(max_length=150,blank=False,null=False,help_text='Add your new App') def __str__(self): return self.name def get_absolute_url(self): return reverse("dashapp:space",kwargs={'pk':self.pk}) class Adspace(models.Model): user=models.ForeignKey(User,related_name='adspace', null=True, default=None,on_delete=models.CASCADE) ad_space=models.CharField(max_length=150,blank=False,null=False) app=models.ForeignKey('Appname', related_name='appnames',default=None, on_delete=models.CASCADE) PID_TYPE = ( ('FN','FORMAT_NATIVE'), ('FNB','FORMAT_NATIVE_BANNER'), ('FI','FORMAT_INTERSTITIAL'), ('FB','FORMAT_BANNER'), ('FMR','FORMAT_MEDIUM,RECT'), ('FRV','FORMAT_REWARDED_VIDEO'), ) format_type=models.CharField(max_length=3,choices=PID_TYPE,default='FN',blank=False, null=False) def __str__(self): return self.ad_space def get_absolute_url(self): return reverse("dashapp:create",kwargs={'pk':self.pk}) Views.py SHowing the one where i need to the query class spacelist(LoginRequiredMixin,ListView): model=Adspace template_name='adspace_list.html' def get_queryset(self): query_set=super().get_queryset() return query_set.filter(user=self.request.user) Here I need to perform One more query so that EACH APP show their own adspaces when clicked right now every app show every show adspaces. I have the idea what to do as if i compare app_id then it'll show the exact app related adspaces, but i dont know how to write query for the same as i already have one query present.??? -
unable to locate websocketbridge.js in Django using channels websocket project
I am trying to implement websockets using channels in Django project. I am getting 404 for webscoketbridge.js Below is html template. {% load staticfiles %} {% block title %}Delivery{% endblock %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link href='https://fonts.googleapis.com/css?family=Satisfy' rel='stylesheet' type='text/css'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="{% static 'channels/js/websocketbridge.js' %}" type="text/javascript"></script> Also, I tried to have a look in the virtualenv/lib/python3.5/site-packages/channels path, there is no js folder or any file named websocketbridge.js Has anyone solved this issue? -
Django: Obtaining verbose_name and help_text for fields added through annotate in custom manager
I'm not sure if I am actually approaching this the right way, but what I would like to do is to be able to give a verbose name and a help text to fields I add to to my model through annotate. I use both these fields as I pass them to the webpage, and use the verbose_name as table header and the help_text as tooltip (basically a call which returns a list of dictionaries with the name of the field, the type, the verbose name and the help text). I get these values by calling Student._meta.get_field(field).verbose_name or help_text. Now the model I use is basically something like this: class Student(models.Model): # new first_name = models.CharField(verbose_name='first name', max_length=30, help_text='The first name of the student') last_name = models.CharField(verbose_name = 'last name', max_length=30, help_text='The last name of the student') date_of_birth=models.DateField(verbose_name='Date of Birth 'help_text = "student's date of birth") sex = models.CharField( max_length=1, choices=(('M','Male'), ('F','Female')), help_text=_('Sex of the student: (M)ale or (F)emale'), verbose_name='Sex')) I then have another model which basically maps the age of a student to its "category" (Freshman-Sophomore-Junior-Senior). My custom manager then adds a new field to the QuerySet which determine the category based on the date of birth and adds … -
Django Admin: Hook admin urls from an app with a namespace
project/urls.py: from django.urls import path urlpatterns = ( path('labs/', include('my_app.urls', namespace='my_app')), ) my_app/urls.py: from django.contrib import admin from django.urls import path app_name = 'my_app' urlpatterns = ( path('admin/', admin.site.urls), ) When I visit 127.0.0.1:8000/labs/admin I get: Traceback (most recent call last): File "/home/user/.virtualenvs/venv/lib/python3.5/site-packages/django/urls/base.py", line 75, in reverse extra, resolver = resolver.namespace_dict[ns] KeyError: 'admin' During handling of the above exception, another exception occurred: ... django.urls.exceptions.NoReverseMatch: 'admin' is not a registered namespace It works as expected, if I set: project/urls.py: urlpatterns = ( path('labs/admin', admin.site.urls), ) I guess that app_name = 'my_app' is the trouble maker. How can I make it work? -
mysqlclient fails to install within virtual environment
Outside my VE, mysqlclient is already installed and works fine, but when I try 'pip install mysqlclient' within my VE I get the following error: "fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory" -
How can I view the pdf file in Django?
Note: My model table consists of id field and File field which will be pdf. I am inserting data into the model using django admin.(I have no custom upload form) I am trying to view the pdf in the browser(as it normally opens in chrome). I am trying to find the file by taking the id field(by user) in a custom HTML template using a form(Please look at the codes mentioned below.) I am attaching the urls.py, index.html, views.py, models.py and forms.py codes below. Please patiently go through and let me the know the problem and the solution. I think my code should work but I am getting a Suspicious File Operation Error. urls.py urlpatterns = [ path('',views.index), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def index(request): if request.method == "POST": form = Form(request.POST) if form.is_valid(): id=request.POST.get("id") ans = query.objects.get(id=id) response=ans.repo if ans is None: return redirect("index.html") else: #return render (request,"ans.html",{'ans':response}) return redirect(response) else: form = Form() return render(request,"index.html",{'form':form}) forms.py class Form(forms.Form): id = forms.CharField(label="Report ID", max_length=100) models.py class query(models.Model): id=models.IntegerField(primary_key=True) repo=models.FileField(upload_to='documents/') index.html <!-- Search Form --> <form id="signup-form" method="POST" action=""> {% csrf_token %} {{form}} <input type="submit" value="Check" /> </form> -
How to count blog categories in django and display them in a template
am new in django am developing a blog which has functions post_list,category_detail and post detail am stuck in post_list function which renders a blog.html i want to display the blog category which are python and hardware together with the total number of posts in that category i have tried my ways it shows the wrong way since there should be six posts in python category and one post in hardware category see the picture here please check the codes and help out views.py def post_list(request): object_list=Post.objects.filter(status='Published').order_by("-created") recent_post=object_list[:4] category_list_count=Post.objects.annotate(num_category=Count('Category')) page = request.GET.get('page', 1) paginator = Paginator(object_list, 3) try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context={ 'items':items, 'recent_post':recent_post, 'category_list_count':category_list_count, } return render(request,"blog.html",context) blog.html <div class="widget"> <h3 class="badge">CATEGORIES</h3> {% for obj in category_list_count %} <ul> <li><a href="{% url 'category_detail' slug=obj.Category.slug %}">{{obj.Category}}</a> <span class="badge">{{obj.num_category}}</span> </li> </ul> {% endfor %} -
Django: use @cached_property decorator to cache queryset result
I am trying to use the cached_property decorator in order to cache the result of a queryset using values_list as follows: class Bar(models.Model): foo = models.ForeignKey('Foo', cascade=models.CASCADE) class Foo(models.Model): @cached_property def bars_pk(self): print('Computing cached property') return list( Bar.objects.filter( foo=self, ).values_list( 'pk', flat=True, )) def has_bar(self, bar): return bar.pk in self.bars_pk for foo in Foo.objects.all(): for bar in Bar.objects.filter(pk__in=[1, 3, 10, 100]): print(foo.has_bar(bar)) Unfortunately, the property bars_pk is always computed. Note that Foo.bars_pk uses list to force queryset evaluation as stated here. For the record, the project uses Python 3.4.4 and Django 1.8.18. Thanks!! -
django rest framework url parameters getting combined
I have the following in my urls.py: url(r'^prstatus/(?P<pk>\d+)/(?P<organization>.+)/' + '(?P<repository>.+)/(?P<pr>\d+)/$',PRStatus.get_pr_status, name="one_pr_in_repo"), The url that I enter is: localhost:8000/api/v1/prstatus/1/myrepo/docker-react/1 But if I print(organization, repository, pr). I get myrepo/docker-react 2 None Organization gets assigned myrepo/docker-react instead of myrepo. Can someone help on this? -
Filtered M2M query sets in selection django admin
I have an event that has many block prices where there are sets of blocks and each set has a price, so I created an M2M field that represents blocs and a positive integer for the price, however, I want to make each set unique so no block can be repeated in another set. Here's my model. class BlocPrice(models.Model): event= models.ForeignKey(Event, on_delete=models.CASCADE) bloc_set= models.ManyToManyField(Bloc) prix = models.PositiveIntegerField() Screenshot of DjangoAdmin: In the change list of the block prices, I want the list of blocks to be filtered each time we select a block so B2, B1 won't be shown in the second input since they were selected in first input, Is there a way to do so? -
I want to build a survey HTML form using DJANGO querysets. please hep urgently. Guide me with steps required
I want to build a HTML form for a simple survey. the survey has three models -: 1. Question(Within that there is a class attribute which has recursive relation in Foreign Key) 2. choices 3. Answers(The data should be saved in JSONField) -
How do I check if a user is in a certain group? Django
I did not understand this solution: In Django, how do I check if a user is in a certain group? Where i should write that solution? in views.py? And what should i write in html template to use it?? Can someone explain me that? Also that(Check Django User Group) is not working too (Invalid filter: 'is_group'). -
The best way to use full-text search in django-filters' FilterSet?
My app uses rest-framework and django-filter. I use this FilterSet to provide filtering list of articles (ModelViewSet) by date: from django_filters import rest_framework as filters class ArticleFilter(filters.FilterSet): start_date = filters.DateTimeFilter(field_name='pub_date', lookup_expr='gte') end_date = filters.DateTimeFilter(field_name='pub_date', lookup_expr='lte') class Meta: model = Article fields = ['pub_date'] I want to add search box to my app, so I need another filter, that will use full-text search at my Article model. Fields I would to search are title and description. I decided to add search field with method parameter like that: from django_filters import rest_framework as filters from django.contrib.postgres.search import SearchVector class ArticleFilter(filters.FilterSet): start_date = filters.DateTimeFilter(field_name='pub_date', lookup_expr='gte') end_date = filters.DateTimeFilter(field_name='pub_date', lookup_expr='lte') search = filters.CharFilter(method='filter_search') def filter_search(self, queryset, name, value): return queryset.annotate(search=SearchVector('title', 'description')).filter(search=value) class Meta: model = Article fields = ['pub_date'] It works, but I'm not sure that it's the best way of using full-text search filtering. Am I missing something or this approach is ok? -
Filtering another model field count for each item from object_list (List View, Django)
I am learining Django trying to create a blog. I have a ListView of Post model on Homepage. I am trying to add new context data (number of comments from separate model Comment for each item from ListView). However I wasn't able to correctly filter number of Comments for each Post by using __in (it just shows same total number of Comments on each Post item of ListView). Could you please help me with how to get a correct filter to show for each ListView Post item how many Comments does it have? Thanks! Post Model: class Post(models.Model): class Meta: verbose_name = 'запись' verbose_name_plural = 'записи' title = models.CharField('название', max_length=300, help_text='Не более 300 знаков') content = models.TextField('текст записи') date_posted = models.DateTimeField('дата публикации', default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='автор') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) Comment model: class Comment(models.Model): class Meta: verbose_name = 'комментарий' verbose_name_plural = 'комментарии' content = models.CharField('текст комментария', max_length=500, help_text='Не более 500 знаков') date_posted = models.DateTimeField('дата публикации', default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name = 'автор') postid = models.ForeignKey(Post, on_delete=models.CASCADE) ListView in views.py: class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self, **kwargs): context = … -
How to autosave Foreignkey value inside my second Model with the id of my first model object.??
I have two models . Appname and Adspace ,I have a Foreignkey object in second model which connects to my first model. Here is the Code models.py class Appname(models.Model): name=models.CharField(max_length=150,blank=False,null=False,help_text='Add your new App') def __str__(self): return self.name def get_absolute_url(self): return reverse("dashapp:space",kwargs={'pk':self.pk}) class Adspace(models.Model): ad_space=models.CharField(max_length=150,blank=False,null=False) app=models.ForeignKey('Appname', related_name='appnames',default=None, on_delete=models.CASCADE) PID_TYPE = ( ('FN','FORMAT_NATIVE'), ('FNB','FORMAT_NATIVE_BANNER'), ('FI','FORMAT_INTERSTITIAL'), ('FB','FORMAT_BANNER'), ('FMR','FORMAT_MEDIUM,RECT'), ('FRV','FORMAT_REWARDED_VIDEO'), ) format_type=models.CharField(max_length=3,choices=PID_TYPE,default='FN',blank=False, null=False) def __str__(self): return self.ad_space def get_absolute_url(self): return reverse("dashapp:view") modelForm class AdspaceForm(forms.ModelForm): class Meta: model=Adspace fields=('ad_space',) Views.py class space(LoginRequiredMixin,CreateView): form_class=forms.AdspaceForm model=Adspace Now I.m unable to fill my form as it says it app_id cannot be null and i'm allowing user to input it. I want that the app which got clicked has its ID in the url (As I'm passing it through there). What should i do that it gets autosave with the same id number by itself that is being passed in the url. -
Django rest framework basic auth for api store in api_credentials table
I want to use Basic Auth for a api which receive JSON data and store in the database table. The problem I faced is to setup Basic Auth for the API. The API username and password store in api_credentials table in 2 separate column. Its has no relation with user table. In my api.py class EventDataViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): queryset = models.EventData.objects.all() serializer_class = serializers.EventDataSerializer authentication_classes = (eventdataapiauth,) # I write this class permission_classes = (permissions.IsAuthenticated,) eventdataapiauth is my auth class. How can I write my authentication code in that class. Or is there any other better way to do this? -
How to read multiple files in django
I have created command in django that reads a csv file and seeds data to the database. Currently, I can only read one file , how can I read multiple files in a directory with the following implementation below. I think I should have some sort of a list of directories and then for each file I will do the seeding. from __future__ import unicode_literals import csv from django.core.management.base import BaseCommand from elite_schedule.models import Match SILENT, NORMAL, VERBOSE, VERY_VERBOSE = 0, 1, 2, 3 import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) x=os.path.join(BASE_DIR, 'matches.csv') class Command(BaseCommand): help = ("Imports movies from a local CSV file. " "Expects title, URL, and release year.") # def add_arguments(self, parser): # # Positional arguments # parser.add_argument("file_path",nargs=1,type=str,) def handle(self, *args, **options): verbosity = options.get("verbosity", NORMAL) file_path = x print(file_path) if verbosity >= NORMAL: self.stdout.write("=== Matches imported ===") with open(file_path) as f: reader = csv.reader(f) # Dont upload header froom csv next(reader) for game in reader: division = game[0] date=game[1] home_team = game[2] away_team = game[3] home_goal = game[4] away_goal = game[5] print(home_goal) home_odd = game[23] draw_odd = game[24] away_odd = game[25] # let's skip the column captions # continue """Assign country based on division. to get divisions code …