Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing user.id to class FormWizardView in Django form-tools
I am trying to create a multi-step form in django2.2. Apparently, the native FormWizard was deprecated in previous django versions so the only solution I have ran into is django-formtools. I have two Models that provide the FormWizard with the required fields. I have been able to make a dictionary of user input from the forms successfully. I intend to save this data to one of the models. However, the model requires a user.id field since it is a Foreign key to a CustomUser object and cannot thereby be null. I believe there is a way to add this user.id to the data dictionary then save the entire dict as an instance in my target model. This is where I have been struggling. I have tried invoking user=request.user but an error occurs saying that 'request is not defined' since this is a class-based view(I guess that's why). My Models class Category(models.Model): name= models.CharField(blank = True, max_length=500) def __str__(self): return self.name class ModelsAd(models.Model): title = models.CharField(max_length=500) category = models.ForeignKey(Category,default=1, on_delete=models.CASCADE) location = models.ForeignKey(Location,default=1, blank=True, on_delete=models.CASCADE) description = models.CharField(max_length=1000) price = models.PositiveIntegerField(default=1000) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.title My Forms all_categories = Category.objects.all() class CategoryChoiceForm(forms.Form): category = … -
Creating a website similar to Knack and managing user apps
I’m just wondering how the Knack website (knack.com) actually manages all the various apps created by dfferent users. Does it actually for example create a postgres database for every new user or its all just one giant database for everyone with access to tables secured to the user that created them? Also is Knack actually a database engine itself or it uses something like postgres or mysql etc. Just wondering if something similar can be created using django. Thanks -
I am new to docker i am creating a drf application using docker so while doing setup i am getting thsi error
ERROR: Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers) i was following this article ... https://wsvincent.com/django-docker-postgresql/ And i am getting this error while running this command- docker-compose run web python /code/manage.py migrate --noinput -
How to you handle error during migration after you add new foreign key
I am learning Django for the last few months and I face a problem with makemigrations file. For example, in the beginning, I added these models: class Booking(models.Model): alias = models.UUIDField( primary_key=True, default=uuid4, editable=False ) seat = models.ForeignKey(Seats, on_delete=models.CASCADE) show = models.ForeignKey(Show, on_delete=models.CASCADE) Also, i run makemigrations and migrate, also added some data... But later i found i need to add another field, so i add this field: booked_by = models.ForeignKey(Person, on_delete=models.CASCADE) and finally my models is below: class Booking(models.Model): alias = models.UUIDField( primary_key=True, default=uuid4, editable=False ) seat = models.ForeignKey(Seats, on_delete=models.CASCADE) show = models.ForeignKey(Show, on_delete=models.CASCADE) booked_by = models.ForeignKey(Person, on_delete=models.CASCADE) and then i run successfully makemigrations command but when i try to run python manage.py migrate command: It throws me an error that i guess you all know what error. but if i run python manage.py migrate -fakeIt works successfull The problem is, when i try to add something from admin templates, it cant add new data and throws me some horrible error and i think you know what kind of error those. I need your help me to know, how do you handle this kind of error? how to fix those? how to add new foregin key after run a … -
Unable to make Reservation in hotel rooms in django
when doing booking, it takes me though a form-wizard-steps that lets me "Choose Your Date"(checks availability),"Choose Your Room"(choosing the type of room),"Reservation" then "Confirmation". After selecting the type of room,it takes me back to "Choose Your Date". kindly need some help on this. bellow are my view. def roombooking(request): try: global room_details, cin, cout, rem monthDays={'01':31,'02':28,'03':31,'04':30,'05':31,'06':30,'07':31,'08':31,'09':30,'10':31,'11':30,'12':31} leapDays={'01':31,'02':29,'03':31,'04':30,'05':31,'06':30,'07':31,'08':31,'09':30,'10':31,'11':30,'12':31} room_details = [] if 'email' in request.session: if request.method=='POST': form = RoomBooking(request.POST) check_in = request.POST.get('checkin') cin = changeDateFormat(check_in) check_out = request.POST.get('checkout') if check_out=='': messages.warning(request,"Checkout date cannot be empty") return render(request,'app/booking.html') cout = changeDateFormat(check_out) dt1 = check_in.split('/') dt2 = check_out.split('/') diff=int(dt2[1])-int(dt1[1]) year = int(dt1[2]) if(year%4==0 and year%100!=0 or year%400==0): days_comp = leapDays[dt1[0]] else: days_comp = monthDays[dt1[0]] rem = days_comp if diff<0: rem = days_comp+diff email = request.session['email'] hotel_name = request.session['hotel'] room_details = [cin,cout,email,hotel_name] return render(request,'app/rooms.html') else: return render(request,'app/booking.html') except: return render(request,'app/index.html') ''' """ def single(request): try: if 'email' in request.session: if request.method=='POST': form = Reservations(request.POST) details = get_form(request,form) name = details[0]+" "+details[1]+" "+details[2] price = rem*1000 price = price*details[10] reservation('single',details,price) avl=get_rooms('single') avl = len(avl) rooms_details = Rooms.objects.filter(roomtype='single').values() det=[] for i in rooms_details: for k,v in i.items(): det.append(v) rs = det[2]-details[10] if(rs<0): rs = 0 Rooms.objects.filter(roomtype='single').update(available = rs) return render(request,'app/reservation.html',{'name':name,'room':details[10],'cin':cin,'cout':cout,'bid':today_date,'price':price,'roomtype':'Single'}) else: avl=get_rooms('single') if len(avl)!=0: return … -
jQuery widgets not working for dynamically added formset forms
I have a form and a related formset in my view/template. For several fields I use widgets: Select2 and a calendar (date-picker) from django admin app. I also use dynamic addition of formset forms. When I render a template for the first time, all widgets work fine. But when I add new formset form, widgets of this new form don't work. I've read existing questions on this kind of problem: 1, 2, 3, 4, but they either not applicable for me, or not helping (2 and 3), or may be I am just doing something wrong (most likely - I'm new to it). Much appreciated for any tips. HTML: {% extends "docs/base.html" %} {% load static %} {% block extrahead %} {{ block.super }} {{ form_matter.media.css }} <link href="/static/django_select2/select2.min.css" type="text/css" media="screen" rel="stylesheet"> {% endblock %} {% block content %} {% if mat_id == None %} <form id="MatterForm" action="{% url 'matter_create_url' %}" enctype="multipart/form-data" method="post"> {% else %} <form id="MatterForm" action="{% url 'matter_edit_url' mat_id=mat_id %}" enctype="multipart/form-data" method="post"> {% endif %} {% csrf_token %} <fieldset> {% for field in form_matter %} <div class="form-row"> {% if field.errors %} <div>{{ field.errors }}</div> {% endif %} <label class="form-label">{{ field.label_tag }}</label> <div class="form-input">{{ field }}</div> </div> {% … -
Emails in my Django app send in the shell, but not when app is running
This exact code works in the shell, but does not work in my view and I have no idea why. There is no error message. The email just never gets sent. from django.core.mail import send_mail send_mail('Account Created','Your account has been created!', 'info@mysite.com',[request.user.email]) -
Django FloatField not auto selected value with Select widget in edit mode
For example, I have a model field named fraction. FRACTION_COUNT = ( (0, '0'), (0.5, '0.5'), (1, '1'), (1.5, '1.5'), (2, '2'), ) class MyModel(models.Model) test_fraction = models.FloatField(choices=FRACTION_COUNT, default=0.5) Then in ModelForm, I tried this self.fields['fraction'] = forms.ChoiceField( choices=FRACTION_COUNT, widget=forms.Select( attrs={ 'class': 'form-control' } ), initial=self.instance.fraction if self.instance and self.instance.pk else 1 ) The problem is that I save fraction as 1. Then in edit mode, the value 1 not auto-selected. I tried some of StackOverflow answer but these won't work for me. Do I miss something? -
How can i pass a read_only_fields into my views.py
I'm trying to get these fields in the response of my endpoint, but the view isn't receiving the parameter read_only_fields, just the one in fields. Serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ('email', 'password', 'firstName', 'middleName', 'firstSurname', 'lastSurname',) read_only_fields = ('is_active', 'is_staff', 'is_doctor') extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} UserView: class ManageUserView(generics.RetrieveUpdateAPIView): """Manage the authenticated user""" serializer_class = UserSerializer authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get_object(self): return (self.request.user) -
How to refresh an html page using ajax in Django?
I know this question has been asked several times, but I cannot find a solution. I cannot connect the method output in views with html page. views def save_form(request): if request.method == 'POST' and 'save' in request.POST: lsection = [5] print("calculate method runs...") return JsonResponse({'lsection':lsection}) "calculate method runs..." is printed only when I do not use ajax. html <form method="post" name="nameForm" id="idForm" action = "/project/save/" enctype="multipart/form-data"> {% csrf_token %} ... <input type="submit" name="save" value="Save"> </form> ajax var frm = $('#idForm'); frm.submit(function (e) { e.preventDefault(); $.ajax({ type: frm.attr('save_form'), url: frm.attr('/project/save/'), //data: frm.serialize(), // I tried this as well data: {}, success: function (data) { alert(data) }, error: function (data) { alert("ajax fails") }, }); }); Question: I do not get lsection list on html, I try alert(data) I get an empty html. How can I get lsection on html? -
django-rest-registration 0.5.1 throws RESET_PASSWORD_VERIFICATION_URL and RESET_PASSWORD_VERIFICATION_URL are not set, even if they are set
I am creating REST api, with Django Rest Framework, and first of all I have to give users the way to register. I saw django-rest-registration as easy way to make this, but when I did everything as is said in Quickstart, my terminal throws those errors: django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (rest_registration.E001) RESET_PASSWORD_VERIFICATION_URL is not set ?: (rest_registration.E004) VERIFICATION_FROM_EMAIL is not set System check identified 2 issues (0 silenced). Here's my code: settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'rest_registration', 'app', ] REST_REGISTRATION = { 'REGISTER_VERIFICATION_ENABLED': False, 'RESET_PASSWORD_VERIFICATION_URL': False, 'REGISTER_EMAIL_VERIFICATION_ENABLED': False, } urlpatterns: urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), path('accounts/', include('rest_registration.api.urls')), ] But, when I tried to change REST_REGISTRATION to this: REST_REGISTRATION = { 'REGISTER_VERIFICATION_URL': 'https://frontend-host/verify-user/', 'RESET_PASSWORD_VERIFICATION_URL': 'https://frontend-host/reset-password/', 'REGISTER_EMAIL_VERIFICATION_URL': 'https://frontend-host/verify-email/', 'VERIFICATION_FROM_EMAIL': 'no-reply@example.com', } and I submitted the request, I saw another error: ConnectionRefusedError at /accounts/register/ + Traceback: Environment: Request Method: POST Request URL: http://localhost:8000/accounts/register/ Django Version: 2.2.3 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'rest_registration', 'app'] 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/fullnamedebian/.local/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File … -
How to send dictionary or data while redirecting in django?
I have made a webapp where I can post images and other users can give a like. But if he already liked the post then it would be Red and by clicking it again it will then unlike the post and if the user didn't liked the post then it will be green and cliking the button will result liking the post. I am able to like and unlike function but I can't change the button color according to the logic. In django we cannot pass a dictionary in redirect('urlname').So is there any possible way to make my button green or red according to that logic given? Codes It is the HTML file {% extends 'navbar-footer.html'%} {% block content %} <style> .btn-like{ color: green; } .btn-dislike{ color: red; } </style> <h1>{{button}}</h1> <h4>This is item number {{item.id}}</h4> <h4>{{ item.title }}</h4> <h4>{{ item.body }}</h4> <button type="button" class="btn {{button}}" onclick="javascript:{document.getElementById('increase_like').submit()}">Like {{item.likes}}</button> <form action="{%url 'increase_like' item.id%}" method="POST" id='increase_like' > {% csrf_token %} <input type="hidden" name="" id=""> </form> <img src="{{item.image.url}}" alt=""> {% for user in voter.voter.all %} <h1>{{user.username}}</h1> {% endfor %} {% endblock %} Views.py def likes(request, item_id): voter_id = Vote.objects.filter(item_product_id=item_id, voter=request.user) if voter_id.exists(): voter_obj = get_object_or_404(Vote, item_product_id=item_id) voter_obj.voter.remove(request.user) item = get_object_or_404(Item_Product, pk=item_id) item.likes = … -
Django Google App Engine, how to serve static files using Google Cloud Storage
I have a Django app running on Google App Engine. I want that all the requests for static content will be served not by the Django app but a Google Cloud Storage bucket on which I've already uploaded all the content that the app needs. The storage bucket has public access and I can see the static content with the browser with urls like this: https://storage.googleapis.com/my-bucket/static/image.jpg Basically what I need to know is how to configure the app.yaml file so that the request like these: https://www.mydjangoapp.com/static/image.jpg will be served by the storage: https://storage.googleapis.com/my-bucket/static/image.jpg With Ngix/Apache this is a standard thing, but how can I achieve this on GCP? I did not find a working solution on the documentation. Thanks -
How to make js function with static variables ? How can i run these functions for every image in the page?
I have a page that contains a list of photos where users may want to input just a part of the images to be processed in the backend. I used CropperJs to crop the images and it did work but when I provided the variable names manually from the console. here's my functions: {% for image in Patient_detail.images.all %} var $image = $("#image{{image.pk}}"); var cropBoxData; var canvasData; $("#modalcrop{{image.pk}}").on("shown.bs.modal", function () { $image.cropper({ viewMode: 1, aspectRatio: 1/1, minCropBoxWidth: 200, minCropBoxHeight: 200, ready: function () { $image.cropper("setCanvasData", canvasData); $image.cropper("setCropBoxData", cropBoxData); } }); }).on("hidden.bs.modal", function () { cropBoxData = $image.cropper("getCropBoxData"); canvasData = $image.cropper("getCanvasData"); $image.cropper("destroy"); }); // Enable zoom in button $(".js-zoom-in").click(function () { $image.cropper("zoom", 0.1); }); // Enable zoom out button $(".js-zoom-out").click(function () { $image.cropper("zoom", -0.1); }); $(".js-crop-and-upload").click(function () { var cropData = $image.cropper("getData"); $("#id_x{{image.pk}}").val(cropData["x"]); $("#id_y{{image.pk}}").val(cropData["y"]); $("#id_height{{image.pk}}").val(cropData["height"]); $("#id_width{{image.pk}}").val(cropData["width"]); $("#formUpload{{image.pk}}").submit(); }); {% endfor %} If i replace {{image.pk}} with 53 for example or any valid/existing number the modal with this number as id will work fine so how should I repeat these function with the different pks should I just replace it with classes ? -
How to change the fields displayed if an instance is passed?
I have a form something like this: class exampleForm(forms.ModelForm): class Meta: model = example fields = ('field1','field2') Now, I want to add an additional field if an instance is passed to it. Which means that, if I create an form with an instance (for editing that object) I want to change the fields being displayed. I know I can use create an another form for this purpose and create an instance of that rather than using this. However, is there a way to do this in this same form? -
form datas are updating in the database instead of **INSERTING** (DJANGO)
I want store the form data into database but when I press the submit button, the rows in the database is updating instead INSERTING from home page I am clicking the link called. fetch_faculty_subject which will retrieve some data from database and shows output as like dropdown list(in HTML ). again from form I am adding some data to the form and storing to the table called Mapped_faculty_n_subjects this is my views.py def fetch_faculty_subject(request): faculties= facultyhours.objects.filter(user_id = request.user.id) subjects= subject_code.objects.filter(user_id = request.user.id) classname= class_number.objects.filter(user_id = request.user.id) context1 = { 'faculties': faculties, 'subjects': subjects, 'classes': classname } return render(request, 'createtimetable_for_class/selecting_subjects_n_teachers.html', context1) def store_the_faculty_subject(request): userr = request.user.id selected_class_name=request.POST["classname"] selected_faculty_name=request.POST["facultyname"] selected_subject_name=request.POST["subjectname"] selected_total_hours_per_week=request.POST["totalhours"] faculty_n_subject_db=Mapped_faculty_n_subjects(selected_class_name=selected_class_name,selected_faculty_name=selected_faculty_name,selected_subject_name=selected_subject_name,selected_total_hours_per_week=selected_total_hours_per_week,user_id=userr) faculty_n_subject_db.save() # return redirect('/fetch_faculty_subject/') faculties= facultyhours.objects.filter(user_id = request.user.id) subjects= subject_code.objects.filter(user_id = request.user.id) classname= class_number.objects.filter(user_id = request.user.id) context1 = { 'faculties': faculties, 'subjects': subjects, 'classes': classname } # return redirect(request,'createtimetable_for_class/selecting_subjects_n_teachers.html',context1) return render(request, 'createtimetable_for_class/selecting_subjects_n_teachers.html',context1) this is my models.py class Mapped_faculty_n_subjects(models.Model): selected_class_name=models.CharField(max_length=250,primary_key=True) selected_faculty_name=models.CharField(max_length=250) selected_subject_name=models.CharField(max_length=250) selected_total_hours_per_week=models.CharField(max_length=250) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) this is my html form {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="row justify-content-center"> <div class="col-6"> <div class="card"> <div class="card-body"> <h2>Select Faculty and Subject</h2> <form method="post" action="/store_the_faculty_subject/"> {% csrf_token %} {{ form|crispy }} <label>Select The Class</label><br> <select … -
Should I be installing virtualenvwrapper globally?
I am completely new to python and I want to learn Django. While following the Django get started tutorial, it says I need to install virtualenv and virtualenvwrapper, which I don't know if I've done correctly. I am using Ubuntu 18.04 I successfully ran the command sudo apt-get install python3-pip. I ran the command pip3 install virtualenv. The result was a directory /home/john/.virtualenvs. I ran the command pip3 install virtualenvwrapper. The result was the file /home/john/.local/bin/virtualenvwrapper.sh. However, the documentation suggests I should see /usr/local/bin/virtualenvwrapper.sh instead, which is not the case. Before I possibly lose countless hours troubleshooting django/python bugs due to environment configuration issues, I'd like to know whether virtualenvwrapper is typically installed at a more global level? Based some things I've read, it seems like .virtualenv is similar to nodejs node_modules folder, where I can choose to install packages locally for a specific project or globally for all projects. And it seems like virtualenvwrapper offers extra utilities that I will be using at a global level. Hence my hesitation and doubt on whether I'm configuring my environment properly. Can someone point me in the right direction? -
Mezzanine framework blogcategory object display on templates
please, how can I insert my blog category from my administration section on my templates. I have created the different blog category on mine administration section but i couldn't display it on my templates. `{% for blog_categories in blog_post.categories.all %} <li><a h ref="">{{ blog_categories }}</a></li> {% endfor %}` -
Unable to make form in Django
I have recently started making a Django web app for a personal project of mine. I have made a model, and makemigrations / migrate works fine. When I made the form, and ran those commands, I received the following error: django.core.exceptions.FieldError: Unknown field(s) (mideals) specified for Sheet. forms.py from django import forms from . import models class CreateSheet(forms.ModelForm): class Meta: model = models.Sheet fields = [ 'name', 'slug', 'Class', 'background', 'race', 'xp', 'level', 'strength', 'dexterity', 'constitution', 'intelligence', 'wisdom', 'charisma', 'strengthMod', 'dexterityMod', 'constitutionMod', 'intelligenceMod', 'wisdomMod', 'charismaMod', 'sStrength', 'sDexterity', 'sConstitution', 'sIntelligence', 'sWisdom', 'sCharisma', 'acrobatics', 'animalHandling', 'arcana', 'athletics', 'deception', 'history', 'insight', 'intimidation', 'investigation', 'medicine', 'nature', 'perception', 'performance', 'persuasion', 'religion', 'sleightOfHand', 'stealth', 'survival', 'acrobaticsMod', 'animalHandlingMod', 'arcanaMod', 'deceptionMod', 'historyMod', 'insightMod', 'intimidationMod', 'investigationMod', 'medicineMod', 'natureMod', 'perceptionMod', 'performanceMod', 'persuasionMod', 'religionMod', 'sleightOfHandMod', 'stealthMod', 'survivalMod', 'otherProficiencies', 'languages', 'equipment', 'copper', 'silver', 'gold', 'platinum', 'armorClass', 'initiative', 'speed', 'maxHitPoints', 'hitPoints', 'hitDice', 'sDeathSave1', 'sDeathSave2', 'sDeathSave3', 'fDeathSave1', 'fDeathSave2', 'fDeathSave3', 'personalityTraits', 'mideals', 'bonds', 'flaws', 'featuresTraits', ] models.py from django.db import models # Create your models here. class Sheet(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(default="") Class = models.CharField(max_length=100) background = models.CharField(max_length=100) race = models.CharField(max_length=100) xp = models.IntegerField() level = models.IntegerField() strength = models.IntegerField() dexterity = models.IntegerField() constitution = models.IntegerField() intelligence = models.IntegerField() wisdom = models.IntegerField() charisma … -
Why do I get an error when I run pip install MySQL-Python?
I am desperately trying to set up django but can't help but continuously run into problems. My problem is when I run "pip install MySQL-python", I run into a wall of text in red and errors that I cannot figure out. Anything is appreciated. I cannot install django and this is my first post on stack overflow, so please be easy on me if I messed up any formatting etc. I am not experienced in coding and the fact that I cannot even get basic stuff like this to work is extremely discouraging. C:\WINDOWS\system32>pip install MySQL-python Collecting MySQL-python Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip Building wheels for collected packages: MySQL-python Building wheel for MySQL-python (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\chrispa\appdata\local\programs\python\python37-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Chrispa\\AppData\\Local\\Temp\\pip-install-ts0ir3mr\\MySQL-python\\setup.py'"'"'; __file__='"'"'C:\\Users\\Chrispa\\AppData\\Local\\Temp\\pip-install-ts0ir3mr\\MySQL-python\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Chrispa\AppData\Local\Temp\pip-wheel-4pjpg8hv' --python-tag cp37 cwd: C:\Users\Chrispa\AppData\Local\Temp\pip-install-ts0ir3mr\MySQL-python\ Complete output (29 lines): running bdist_wheel running build running build_py creating build creating build\lib.win32-3.7 copying _mysql_exceptions.py -> build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants … -
edit Meta of db_table at runtime django
I want a dynamic django Model to point to different db tables at runtime. What I tried is to declare the model myModel inside a view in views.py, that way i can create a model everytime i access that view and set everytime a different db table (not including the model myModel in models.py). Doing so though, i get an error at runtime: RuntimeWarning: Model 'myModel' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models. and also i'm pretty sure this is not the way to go.. I'm assuming the best thing to do is to declare a single myModel in models.py and edit the field db_table = 'sometable' in the Meta class of the model but i really don't know how to achieve that. Is there an easy way to do it? I tried to follow this link but i didn't understand much.. I don't know if this can be helpful Django model: change db_table dynamically Thank you -
TypError: 'ManyRelatedManager' object is not iterable when tyring to override serializer's create and add M2M field
I am trying to override DRF's ModelSerializer so that I can pass it a list of RemoteServer pk's and it will create TaskTarget instances with the server field equal to the server. The serializer that is giving me issues: class RemoteTaskSerializer(serializers.ModelSerializer): targets = serializers.ListField(child=serializers.IntegerField()) class Meta: model = RemoteTask fields = ("name", "targets", "id") def create(self, validated_data): server_ids = validated_data.pop('targets', []) remote_task = RemoteTask.objects.create(**validated_data) for pk in server_ids: t = TaskTarget(server=RemoteServer.objects.get(pk=pk)) t.save() remote_task.targets.add(t) return remote_task Models: class RemoteTask(models.Model): name = models.CharField(max_length=120, unique=True) targets = models.ManyToManyField(TaskTarget) class TaskTarget(models.Model): server = models.ForeignKey("RemoteServer", on_delete=models.CASCADE) output = models.TextField(null=True) huey_id = models.IntegerField(unique=True, null=True) class RemoteServer(models.Model): name = models.CharField(max_length=120, unique=True) ip = models.GenericIPAddressField() port = models.PositiveIntegerField() The idea is that I could do send this to RemoteTaskSerializer: { // RemoteServer pk's targets: [1,2,3] // Rest of fields name: "Test" } And I would end up with three TaskTarget instances in RemoteTask.target, the first one pointing to TaskTarget(server=RemoteServer.objects.get(pk=1)), and so on. -
Optimizing dfs in django
I have users in some kind of a tree that represents my affiliate system. I need to get and count all users that are under me in the tree (my partners). I've implemented modified version of deep first search algorithm but it works slow because it makes a lot of calls to database to get each user and their partners. How I can optimize all this process to work faster? User model class User(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(default="", max_length=30, blank=True) invited_by = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) partners = models.ManyToManyField('self', blank=True) # here are all user's partners wallet = models.CharField(blank=True, max_length=128) level = models.PositiveIntegerField(default=0) turnover = models.FloatField(default=0.0) created = models.DateTimeField(default=timezone.now) That's my dfs function. It accepts current User object and returns list of users that are under him in this tree def dfsgetlist(user): q = [] for i in user.partners.all(): if i != user and i != user.invited_by: q += dfsgetlist(i) return q + [user] -
Template does not exist (Django)
I get the following message with Django. I use the instructions of Django with visual studio code tutorial of Microsoft. I don't know how to solve this enter image description here -
Which is more efficient (Django models)
initially, i have 3 games (lol, dota2, hearthstone) and game count can increase lol has team vs team based match dota 2 has team vs team based match hearthstone have player vs player based match I am modelling the database to keep match histories of these games. Which one is more efficient. If none of them are not efficiently, what should you suggest in addition, Database have the tournament and league tables class Game1(models.Model): type_tvt = 1 type_pvp = 2 type_royale=3 types = ( (type_tvt, 'Takım vs Takım Klasik'), (type_pvp, 'Player vs Player Klasik'), (type_royale,'Battle Royale Takımlar vs Takımlar'), ) gametype=models.SmallIntegerField(choices=types,verbose_name="Oyun Tipi") name=models.CharField(max_length=255,blank=True,null=True) slug = models.SlugField(unique=True, max_length=255) player1=models.ForeignKey(Player,on_delete=models.CASCADE,related_name='p1',null=True,blank=True) team1=models.ForeignKey(Team,on_delete=models.CASCADE,related_name='t1',null=True,blank=True) team1player = models.ManyToManyField(Player,blank=True,related_name='mp1') score1 = models.PositiveSmallIntegerField(null=True, blank=True) player2=models.ForeignKey(Player,on_delete=models.CASCADE,related_name='p2',null=True,blank=True) team2=models.ForeignKey(Team,on_delete=models.CASCADE,related_name='t2',null=True,blank=True) team2player=models.ManyToManyField(Player,blank=True,related_name='mp2') score2 = models.PositiveSmallIntegerField(null=True, blank=True) game=models.ForeignKey(OnlineGame,on_delete=models.CASCADE,null=True,blank=True,related_name="matchgame",verbose_name="Oyun") ... OR (GameTvT and GamePvP) class Game2(models.Model): name=models.CharField(max_length=255,blank=True,null=True) slug = models.SlugField(unique=True, max_length=255) score1 = models.PositiveSmallIntegerField(null=True, blank=True) score2 = models.PositiveSmallIntegerField(null=True, blank=True) game=models.ForeignKey(OnlineGame,on_delete=models.CASCADE,null=True,blank=True,related_name="matchgame",verbose_name="Oyun")... class Meta: abstract = True class GameTvT(Game2): team1=models.ForeignKey(Team,on_delete=models.CASCADE,related_name='t1',null=True,blank=True) team1player = models.ManyToManyField(Player,blank=True,related_name='mp1') team2=models.ForeignKey(Team,on_delete=models.CASCADE,related_name='t2',null=True,blank=True) team2player=models.ManyToManyField(Player,blank=True,related_name='mp2')... class GamePvP(Game2): player1=models.ForeignKey(Player,on_delete=models.CASCADE,related_name='p2',null=True,blank=True) player2=models.ForeignKey(Player,on_delete=models.CASCADE,related_name='p2',null=True,blank=True)... OR class lol(models.Model): .... class dota2(models.Model): .... class heartstone(models.Model): ....