Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I fill the table correct in Django template?
I want to fill the table in a correct way (see the picture). But I can't do it without changing a model or using tables2 app. How I can go through Teams and get 1 player for each team and then go next line for a table? What I have now: Correct and wrong tables models.py: from django.db import models class Server(models.Model): name = models.CharField(max_length=16) url = models.CharField(max_length=64) class Team(models.Model): server = models.ForeignKey(Server, on_delete=models.CASCADE) name = models.CharField(max_length=16) n_players = models.IntegerField(null=True) class Player(models.Model): server = models.ForeignKey(Server, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) name = models.CharField(max_length=16, null=True) highlight = models.BooleanField(default=False) views.py: from django.shortcuts import render from .models import Server, Team def index(request): server_list = Server.objects.order_by('name')[:3] context = {'server_list': server_list} return render(request, 'monitor/index.html', context) templates index.html: {% for server in server_list %} <h2>{{ server.name }}</h2> <table> <tr> {% for team in server.team_set.all %} <th> <b>{{ team }}</b> </th> {% endfor %} </tr> {% for team in server.team_set.all %} <tr> {% for player in team.player_set.all %} <td>{{ player }}</td> {% endfor %} </tr> {% endfor %} </table> {% endfor %} -
Django DecimalField returns strings
I have this model: class Item(models.Model): amount = models.DecimalField(max_digits=15, decimal_places=2) quantity = models.DecimalField(max_digits=15, decimal_places=6) total = models.DecimalField(max_digits=15, decimal_places=2) def save(self, *args, **kwargs): ## Following lines are for debugging only print(self.amount) print(self.quantity) print(type(self.amount)) print(type(self.quantity)) self.total = self.amount*self.quantity super(Item, self).save(*args, **kwargs) What I"m trying to do here is to automatically calculate and save the total value (quantity*amount). This is something I need to have available as a field but it should be calculated automatically. However, I get this error: can't multiply sequence by non-int of type 'str' When I look at the print() and print(type()) results... I see that indeed, these fields are strings even though they contain the numbers I expect: 982.00 0.008300 <class 'str'> <class 'str'> Why does this happen? -
how to in simply wey required BooleanField at form in django
class Participant(models.Model): first_name = models.CharField(max_length=50, verbose_name='Imię') last_name = models.CharField(max_length=50, verbose_name='Nazwisko') email = models.EmailField(verbose_name='E-mail') nr_telefonu = models.CharField(max_length=11, blank=True, verbose_name='Nr telefonu') regulamin_1 = models.BooleanField(default=False, verbose_name='Wyrażam') regulamin_2 = models.BooleanField(default=False, verbose_name='Wyrażam') created = models.DateTimeField(auto_now_add=True) What i cen do to required BooleanField from user. when you tried to use the required = True argument still didn't work. Is there anyone who can resolve that problem? def home(request): #return HttpResponse("hi"); form = ParticipantCreateForm(request.POST or None) if form.is_valid(): form.save() context = {'form': form } return render(request, 'apka/base.html', context) -
How To Change Default Fields In Django Login Form
As we know that the default Django login page form fields are the username and the password, however, I wanted to change the login fields to Email and Password, as I think that it's easy for people to login with their email than their username. And Also because the web app I'm trying to create doesn't need a username field. So, How Can I Change the fields to Email And Password? I used this code to change the fields in the Forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegistrationForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['email', 'password1', 'password2'] Views.py: from django.shortcuts import render, redirect from .forms import UserRegistrationForm def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = UserRegistrationForm() return render(request, 'users/register.html', {'form': form}) Any Help Would Be Appreciated! -
two forloop in 1 table row
<table> {% for sensie in teacher %} <tr style='height:19px;'> <th id="703183278R34" style="height: 19px;" class="row-headers-background"> <div class="row-header-wrapper" style="line-height: 19px;">35</div> </th> <td class="s46"></td> <td class="s51" colspan="3">{{sensie.Subjects}}</td> <td class="s51" colspan="4">{{sensie.Employee_Users}}</td> {% endfor %} {% for room in roomsched %} <td class="s51" colspan="6">{{room.Classroom}}-{{room.Day_Name}}</td> </tr> {% endfor %} </table> \views teacher = SubjectSectionTeacher.objects.filter(Education_Levels__in=studentenroll.values_list('Education_Levels')) roomsched = SubjectRoomSchedule.objects.filter(Subject_Section_Teacher__in=teacher) return render(request, 'Homepage/enrollmentrecords.html',{,"teacher":teacher,"roomsched":roomsched}) how do i make it properly formatted in table row just like this in the example shown below. please help me.... Subject Teacher Room math teachername room512 -
Django Smart Select Chained Dropdown Not Working
Im trying to learn django smart select but I can't seem to get my chained drop down to work. My models are from django.db import models from smart_selects.db_fields import ChainedForeignKey class Continent(models.Model): name = models.CharField(max_length=255) class Country(models.Model): continent = models.ForeignKey(Continent, on_delete=models.CASCADE) name = models.CharField(max_length=255) class Location(models.Model): continent = models.ForeignKey(Continent, on_delete=models.CASCADE) country = ChainedForeignKey( Country, chained_field="continent", chained_model_field="continent", show_all=False, auto_choose=True, sort=True) city = models.CharField(max_length=50) street = models.CharField(max_length=100) In my admin page from django.contrib import admin from .models import Location, Continent, Country class LocationAdmin(admin.ModelAdmin): pass admin.site.register(Location, LocationAdmin) class ContinentAdmin(admin.ModelAdmin): pass class CountryAdmin(admin.ModelAdmin): pass admin.site.register(Continent, ContinentAdmin) admin.site.register(Country, CountryAdmin) In urls.py I did urlpatterns = [ path('admin/', admin.site.urls), url(r'^chaining/', include('smart_selects.urls')), ] In settings.py I did INSTALLED_APPS = [ 'smart_selects', 'location.apps.LocationConfig', 'sales.apps.SalesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', ] USE_DJANGO_JQUERY = True I input the continents Asia and Europe and add Poland to Europe and China to Asia. However when I try to add a location its not population the second dropdown. What am I doing wrong? -
Is there a way to send Json payload from a Django REST Created API as payload too another API?
I created an API with Django REST Framework, I want to use Django REST to submit the Json I have created to submit as Payload to another API. I am not able to see it on the documentation. class CreateListMulesoftRequestAPI(generics.ListCreateAPIView): queryset = MulesoftStreamRequest.objects.all() serializer_class = MulesoftRequestSerializer # Where validation for Mulesoft goes : @validate_mulesoft_request_create_request_data def post(self, request, *args, **kwargs): ###I believe I should be able to submit to the difference url here### MulesoftAccessRequest = MulesoftStreamRequest( group =request.data.get("group"), users =request.data.get("users"), notes=request.data.get("notes"), correlation_id =request.data.get("correlation_id"), short_description=request.data.get("short_description"), ) MulesoftAccessRequest.save() return Response( data=MulesoftRequestSerializer(MulesoftAccessRequest).data, status=status.HTTP_201_CREATED ) I would like to know if what I am doing is actually possible. -
The code runs normally but there are no messages (django view)
code is this def category_minus_1_for_current_user(request): # ca=Category.objects.filter(id=category_num) ca_num = request.POST['current_ca_num'] # 입력한 ca 번호 print("ca_num check : ", ca_num) print("ca_num type :",type(ca_num)) data = {'ca{}'.format(x-1): F('ca{}'.format(x)) for x in range(99,int(ca_num)-1,-1)} CategoryNick.objects.filter( author=request.user ).update(**data) skil_note = MyShortCut.objects.filter(Q(author=request.user)) if(int(ca_num)>1): ca_delete_num = int(ca_num)-1 ca_delete=Category.objects.get(id=ca_delete_num) MyShortCut.objects.filter(Q(author=request.user) & Q(category=ca_delete)).delete() for sn in skil_note: # print("sn.category.id : ", sn.category.id) if(sn.category.id >= int(ca_num) and sn.category.id != 1): # ca=Category.objects.get(id=int(sn.category.id)+1) print("sn.category.id : ", sn.category.id) print("int(sn.category.id)-1 : ", int(sn.category.id)-1) ca = Category.objects.get(id=int(sn.category.id)-1) # if(ca.id != 100): MyShortCut.objects.filter(id=sn.id).update(category=ca) return JsonResponse({ 'message': "ca"+ca_num+"-1 is success" }) No message is printed and an error message is printed Update is normal but json message is not displayed. if you know what is problem thanks for let me know [14/Oct/2019 23:08:02] "POST /wm/myshortcut/category_minus_1_for_current_user HTTP/1.1" 200 63 Traceback (most recent call last): File "C:\Users\hyunsepk\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\hyunsepk\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\hyunsepk\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\hyunsepk\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\hyunsepk\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Users\hyunsepk\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Users\hyunsepk\AppData\Local\Programs\Python\Python36\lib\socketserver.py", line 775, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] The current connection was interrupted by the software of your host system -
Insert foreighn data inside RAW SQL statement in migration file in Django
Question is regarding custom migration file. from django.db import migrations from django.contrib.contenttypes.models import ContentType class Migration(migrations.Migration): dependencies = [ ('api', '0007_auto_20191013_1553'), ] try: con = ContentType.objects.get_by_natural_key(app_label='api', model='product') model = ContentType.model_class(con) db_table = model._meta.db_table operations = [ migrations.RunSQL( """ DROP TRIGGER IF EXISTS text_searchable_update ON %(db_table)s; """, {'db_table': db_table} ), migrations.RunSQL( """ CREATE TRIGGER text_searchable_update BEFORE INSERT OR UPDATE ON %(db_table)s FOR EACH ROW EXECUTE FUNCTION tsvector_update_trigger(textsearchable_index_col, 'pg_catalog.english', description) """, {'db_table': db_table} ) ] except ContentType.DoesNotExist: operations = [] Goal of this migration is to create trigger on db column textsearchable_index_col to update stored vector in case description column is created or updated. Problem is I want to make sure that trigger is created on proper table in case of db_table name would get changed. So that I get db_table = model._meta.db_table and I want to insert db_table value in the raw SQL statement, but seem like I dont know how to do it. In the example in Django docs they use %s formattig but it raises SQL syntax error during migration process. Question is how to insert db_table or any foreign data in wide sense inside this SQL command. Thanks -
Setup for Cookiecutter Django App to serve static files with S3 is not working
I am running a cookiecutter django app and want to use AWS S3 to store my static files. I configured a bucket with policies and have my static files in there. I am struggling with the correct django settings though which look like this right now: DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" AWS_ACCESS_KEY_ID = "mykey" AWS_SECRET_ACCESS_KEY = "mysecretkey" AWS_STORAGE_BUCKET_NAME = "mybucketname" AWS_QUERYSTRING_AUTH = False AWS_S3_CUSTOM_DOMAIN = "foldername" + '.s3.amazonaws.com' # Static media settings STATIC_URL = 'https://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/' #MEDIA_URL = STATIC_URL + 'media/' STATIC_ROOT = 'staticfiles' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) AWS_DEFAULT_ACL = None I had to uncomment MEDIA_URL = STATIC_URL + 'media/' because if I leave it, it tells me runserver can't serve media if MEDIA_URL is within STATIC_URL. Also in my urls I had to change + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) with static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) at the end of my url patterns. I assume that given the correct settings, django should just enter the static folder that is on AWS and follow the paths from there correct? Now, whenever I run my server locally the static files are not served. My css and my logos are not appearing. Is there something I am … -
How to group URIs using drf-yasg generator?
Some time ago I was using django-rest-swagger (which is no longer maintained) as documentation generator for my API, and one particular thing was very handy: it automatically grouped related URI's by their path. Recently I switched to drf-yasg, which clearly is more advanced and powerfull than its predecessor, although I cannot understand how to group URIs. I have rather vast list of endpoints for mobile client, web, bots and several other things so grouping is crucial for developer to find their way around all available endpoints. For example before switching to drf-yasg this list of endpoints was very beutifully grouped together under single collapsible menu: ... path( 'reservations/', views.ReservationViewSet.as_view({'get': 'list', 'post': 'create'}), name='list-reservations' ), path( 'reservations/<uuid:pk>/', views.ReservationViewSet.as_view({'get': 'retrieve', 'patch': 'partial_update'}), name='retrieve-reservation' ), path( 'reservations/<uuid:pk>/confirm', views.ReservationStatusViewSet.as_view({'put': 'confirm'}), name='confirm-reservation' ), path( 'reservations/<uuid:pk>/decline', views.ReservationStatusViewSet.as_view({'put': 'decline'}), name='decline-reservation' ), path( 'reservations/<uuid:pk>/check-in', views.ReservationStatusViewSet.as_view({'put': 'check_in'}), name='check-in-reservation' ), path( 'reservations/<uuid:pk>/no-show', views.ReservationStatusViewSet.as_view({'put': 'no_show'}), name='no-show-reservation' ), path( 'reservations/<uuid:pk>/cancel', views.ReservationStatusViewSet.as_view({'put': 'cancel'}), name='cancel-reservation' ), path( 'reservations/<uuid:pk>/revert', views.ReservationStatusViewSet.as_view({'put': 'revert'}), name='revert-reservation' ), ... Yet now for whatever reason it's just being thown as plain list together with all other endpoints so it became bery difficult to quickly find and distinguish relevant endpoints (as you see there are multiple groups of endpoints that logically should … -
Django : Chunck queryset about 1000 object for update
I have about 50000 data in this object for update I need to chunck in at 1000 at a time instance_list = Stock.objects.filter( status=Status.ACTIVE, organization=self.request.user.organization, **stock_specific_attribute_filter(self.request.GET), ) -
How to log data to database in Django without html redirect
I have been attempting a difficult task with django and I am curious if I am thinking about the nature of the beast in the correct way, and if so if anybody could provide guidance in understanding how to achieve the goal I am hoping to accomplish. I am attempting to create a webapp that can log information without redirecting the url. I have created a small django project which demonstrates a similar task in a much simpler way. Here is the html page that is included in the http reponse to loading the index page. <p>The purpose of this is to log moments we like in the video</p> {% load static %} <video id="myVideo" width="320" height="240" controls> <source src={% static some/static/movie/path.mp4 %} type="video/mp4"> Your browser does not support the video tag. </video> <button onclick="getTime('goodMoment')">Click Here to Mark Time of awesome moment</button> <p id = "goodMoment"></p> <p> Now I would like to log the string that was posted to "goodMoment" as the "time_string" field for a new instance of the model "SavedTime"</p> <p> however, it is important that there is no http response to take us away from this page, because the video needs to continue playing</p> {% load static … -
recommendation required for buidling a new app
I am very new to programming and am after some advice. At work, we run a soccer score predictor whereby each person enters a score for all the games and gets 3 points for a correct score and 1 point if they get the result correct but not the score. It is a very manual process of inputting scores into Excel and getting results, so I want to build an app. I've done a small amount of work with Django and Python in the past. Does anyone care to recommend a language that would be best suited for this task? Thanks -
Docker run /build in CI with different settings file for test stage
I had gitlab-ci.yml that runs postgres container and then builds a web container. The web container has setting.py with DATABASES setup. .gitlab-ci.yml : ... test: stage: test script: - docker run --name db -d postgres:9.6 - docker build --pull -t test_image . - docker run --name myweb ...blah-blah ... setting.py .... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbname', 'USER': 'dbuser', 'PASSWORD': 'dbpassword', 'HOST': 'db', 'PORT': '5432', #or nothing, worked either way } } .... All that worked fine until some recent changes. The changes were: DATABASE section was moved out of settings.py into postgres.py (in the same directory withg settings.py) with hard-coded values replaced with os.environ.get('SOME VAR') calls and settings.py is now imported into postgres.py: postgres.py from <mywebapp>.settings.settings import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('DB_NAME', ''), 'USER': os.environ.get('DB_USER', ''), 'PASSWORD': os.environ.get('DB_PASS', ''), 'HOST': os.environ.get('DB_HOST', ''), 'PORT': '5432', } } Obviously, that does not agree with the docker which now can not find any of the DB config vars ('ENGINE', 'NAME', etc) and I got to fix it. The error is relatively descriptive (from - docker build --pull -t test_image ., not from "- docker run ..."): django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the … -
Queryset difference based on one field
I am trying to compare two querysets based on a single field. But I can't figure out most efficient way to do it. This is my model and I want to check if old and new room_scans(ForeignKey) has PriceDatum's with the same checkin date. if not, create PriceDatum with that checkin date related to the new room_scan. class PriceDatum(models.Model): """ Stores a price for a date for a given currency for a given listingscan Multiple such PriceData objects for each day for next X months are created in each Frequent listing scan """ room_scan = models.ForeignKey(RoomScan, default=1, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) checkin = models.DateField(db_index=True, help_text="Check in date", null=True) checkout = models.DateField(db_index=True, help_text="checkout date", null=True) price = models.PositiveSmallIntegerField(help_text="Price in the currency stated") refund_status = models.CharField(max_length=100, default="N/A") # scanned = models.DateTimeField(db_index=True, help_text="Check in date", null=True) availability_count = models.PositiveSmallIntegerField(help_text="How many rooms are available for this price") max_people = models.PositiveSmallIntegerField(help_text="How many people can stay in the room for this price") meal = models.CharField(max_length=100, default="N/A", help_text="Tells if breakfast is included in room price") Below is the code what I am trying to do: previous_prices_final = previous_prices.filter(refund_status='refund', current_prices_final = current_prices.filter(refund_status='refund', max_people=max_people_count,meal=meal).order_by().order_by('checkin') if len(previous_prices_final) > len(current_prices_final): difference = previous_prices_final.difference(current_prices_final) for x in difference: PriceDatum.objects.create(room_scan=x.room_scan, room=x.room, checkin=x.checkin, … -
What is the best way to stream video from webcam or raspberry pi on a web application (using Django)?
Web application based on the human action recognition model, simply its purpose is to classify actions appear in a streaming video (webcam, raspberry pi .. ), how to do this using Django framework? -
How to change the queryset returned based on the URL
I am trying to make an educational site and have made a category system. There is a URL for each category and I need change the queryset returned based on the URL I am on. For example if I am on "localhost:8000/posts/category/3", I want my queryset returned to be: Post.objects.filter(category=3).order_by('-date_posted') And so one depending on the URL. I don't quite know where to start from for this. The class based view that returns the queryset: class CatPostListView(ListView): model = Post template_name = 'blog/science.html' #This is when you click a profile in a post, it takes you to his posts only context_object_name = 'posts' paginate_by = 15 def get_queryset(self): return Post.objects.filter(category=2).order_by('-date_posted') urls.py (Contains only the part necessary): urlpatterns = [ path('post/category/<int:pk>/', CatPostListView.as_view(), name='category') ] And just in case models.py: class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.SET_NULL) class Meta: # enforcing that there can not be two categories under a parent with same slug # __str__ method elaborated later in post. use __unicode__ in place of # __str__ if you are using python 2 unique_together = ('slug', 'parent',) verbose_name_plural = "categories" def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() category … -
Adding data to queryset in ModelViewSet
My ViewSet has two methods implemented: list() and get_queryset(). queryset operates on all objects of a model. It's used for filtering data without usage of DjangoFilterBackend. I'm interested in adding an extra field to the response when specific quantity of records is returned, e.g.: if len(queryset) > 1: resp = {"message": "Narrow down filter criteria."} elif len(queryset) == 0: resp = {"message": "No results found."} else: resp = {"message": "OK"} When I run the code, prints placed in list() and get_queryset() appear in the following order: 'list()' checking in... 'get_queryset() checking in... It seems that all changes applied in list() method are overwritten by get_queryset(). Otherwise, this answer would have helped. Is there any other way to return the queryset enriched by additional data, resp in this case? -
What is the best way to create referral links for my django web app?
I want to implement a referral system in my django web app, but i'm confused on how to go about it. What is the best way to implement a referral system whereby a user can share a link typically the signup page with his referral link. when the new user signs up, this will be recorded somewhere and when the new user creates takes certain actions on the site the user who invited him will get a bonus. -
Python Django ListView not calling get_queryset
Our group is trying to use the listview class to display all of the posts in a list format to the user in a news feed style. We created the ListView class with a valid 'template_name' and 'context_object_name'. Then, we implemented the get queryset to retrieve all of the posts from the db ('all()' method): class PostsView(generic.ListView): template_name = 'home.html' context_object_name = 'all_posts_list' def get_queryset(self): return Post.objects.all() However, this get_queryset method is not being run when we call the view. When I have built other apps in the past, the get_queryset was called automatically for my ListView objects, as it should according to the ListView documentation. Does anyone have any suggestions? -
DRF Nested Serializer
I am going to add products to my cart and as we know it is done by Product FK but it looks like this { "id": 1, "user": 1, "product": 1, "name": "iphone X", "price": "500.00", "quantity": 1, "total": 500 }, { "id": 2, "user": 1, "product": 2, "name": "Samsung", "price": "500.00", "quantity": 1, "total": 500 } as it can be seen user: 1 has two product and cart id is different the problem I am facing that is Order which should be taken from cart. class Order(models.Model): user = mo`enter code here`dels.ForeignKey(User, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) total_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) here I can place order for only one product but I do not want this because I have 2 products in my cart my serializer is like this class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ('user', 'cart', 'total_price', 'date_ordered') I want to place order for all products I have in my cart but I need help because please. I am new to Django. Any idea please how to solve this problem? Thank you! -
Best way to create user information table into two tables and connected with OneToOne relation
Please guide and suggest me the best way to solve this problem. I have a user information table: first: username, first_name, last_name, email, password [ provided by django ] Second: mobile, parent_id and other user profile related details [ want to create ] Goal: I want the second table with some fields and connect with the auth_user ( the name provided by django ) through OneToOne relation so I can fectch all the field through one object. What I have tried 1 case I created a second table and connect with FK relation and download all previous data from the previous DB and sperate data manually and uploaded through CSV into new tables. Problem: I cannot access both table data through a single object. 2nd case So I update the second table with OneToOne relation. Problem: add new users with this relation is perfectly fine but when trying to edit/ change previously saved data then got error error: invalid literal for int() with base 10 during change in models Note: Hundreds of user in the previous table, just safly migrate with new DB schema. Please, give me a tricky idea to fix this issue. Thanks to all. Kudos to the … -
The 'cover' attribute has no file associated with it. Django
I want to display person pictures in a table with their name and surname columns. When i put as source static it show pictures but when i send request to database it didn't show. And its already insert data and pictures to database and show picture in /media/images/some.jpg. view.py: def viewpost(request): person_list = Persona.objects.all() if request.method == 'POST': if request.POST.get('name') and request.POST.get('surname') and request.POST.get('address'): person = Persona() person.name = request.POST.get('name') person.surname = request.POST.get('surname') person.address = request.POST.get('address') person.age = request.POST.get('age') person.cover = request.FILES['cover'] person.save() return HttpResponseRedirect('/viewpost') else: return render(request, 'mysite/viewpost.html', {'persons': person_list}) model.py: class Persona(models.Model): name = models.CharField(max_length=255, unique=False) surname = models.CharField(max_length=255, unique=False) address = models.TextField() age = models.CharField(max_length=255, unique=False) cover = models.ImageField(upload_to='images/') and template: <td ><img src="{{person.cover.url}}" class="img-responsive" width="40px" id="pop" data-toggle="modal" data-target="#myModal"/></td> -
How to implement JWT auth in Django with custom endpoint?
I'm learning Django ecosystem and trying to figure out how to implement JWT authentication outside of "hello world" way provided by simplejwt library (trying to build realworld.io REST API). I can't understand how can I do that: should I use simplejwt library or pyjwt and create my custom authentication logic. For example, I want to be able to: POST /users and with { "email": "test@example.com", "password: "password" } and get result back { "email": "test@example.com", "password: "password", "token": <JWT_TOKEN_HERE> } and be able to authenticate myself by sending Authentication header with Bearer <JWT_TOKEN_HERE> https://github.com/davesque/django-rest-framework-simplejwt let's me create 2 endpoints with built-in functionality, but I want to customize it for my own.