Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create/Update operations with nested serializers
I, as a newbie Django developer, am trying to build a RESTful API for a mobile app. I've took over an existing project and previous developers have used Django REST Framework. Super cool package, easy to work with so far. Except for one thing... There is this problem when I want to create new resources, which happen to have nested serializers. I'm not great on explaining software issues with words, so here is the simplified version of my case: class UserSerializer(serializers.ModelSerializer): company = CompanySerializer() # other props and functions are unrelated class CompanySerializer(serializers.ModelSerializer): # props and functions are unrelated Now with this structure, GET /users and GET /users/{id} endpoints work great and I get the results I expect. But with POST /users and PATCH /users/{id} I get a response that says I need to provide an object for company prop and it should resemble a Company object with all the required props, so that it can create the company too. And I'm sure it tries to create a new company because I've tried sending { company: { id: 1 } } and it simply ignores the ID and requires a name to create a new one. This is obviously not β¦ -
ModelForm : validate UniqueConstraint when one of the fields is not included in the form
I have a model called Note. Each Note belongs to a User. A Note must have a code that is unique among all the Notes of the User it belongs to, hence the UniqueConstraint. NoteForm does not include the field owner, since -obviously- I want it to be filled automatically (the user should not be able to choose that). """core/models.py""" from django.db import models from django.contrib.auth.models import User class Note(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='note') code = models.CharField(max_length=60) ... class Meta: constraints = [ models.UniqueConstraint(fields=['code', 'owner'], name='code_unique_per_user') ] """core/forms.py""" from django import forms from core.models import Note class NoteForm(forms.ModelForm): class Meta: model = Note fields = ( 'code', ... ) """core/views.py""" from core.models import Note from core.forms import NoteForm def create_note(request): note = Note(owner=request.user) if request.method == "POST": form = NoteForm(request.POST, instance=note) if form.is_valid(): form.save() return redirect(reverse('core:manage_notes')) else: form = NoteForm(instance=note) args = {'form': form} return render(request, 'core/create_note.html', args) Now when creating a Note using NoteForm, the UniqueConstraint is not checked during validation, because the form does not include the onwer field. What would be the best way to make this UniqueConstraint validation happen ? Including the owner field and setting it as hidden works, but doesn't feel right, because β¦ -
Why is pytest not running my tests and skipping them
I am using pytest-django to test my django application. My directory structure is like this : . βββ Dockerfile βββ Pipfile βββ Pipfile.lock βββ README.md βββ app β βββ __pycache__ β β βββ test_example.cpython-37-pytest-5.2.1.pyc β βββ app β β βββ __init__.py β β βββ __pycache__ β β β βββ __init__.cpython-37.pyc β β β βββ settings.cpython-37.pyc β β β βββ urls.cpython-37.pyc β β βββ settings.py β β βββ urls.py β β βββ wsgi.py β βββ core β β βββ __init__.py β β βββ __pycache__ β β β βββ __init__.cpython-37.pyc β β β βββ admin.cpython-37.pyc β β β βββ models.cpython-37.pyc β β βββ admin.py β β βββ apps.py β β βββ migrations β β β βββ 0001_initial.py β β β βββ __init__.py β β β βββ __pycache__ β β β βββ 0001_initial.cpython-37.pyc β β β βββ __init__.cpython-37.pyc β β βββ models.py β β βββ tests β β βββ __init__.py β β βββ __pycache__ β β β βββ __init__.cpython-37.pyc β β β βββ test_admin.cpython-37-pytest-5.2.1.pyc β β β βββ test_models.cpython-37-pytest-5.2.1.pyc β β βββ test_admin.py β β βββ test_models.py β βββ db.sqlite3 β βββ manage.py β βββ pytest.ini β βββ test_example.py βββ docker-compose.yml The file : test_models.py is like below : from django.contrib.auth import get_user_model β¦ -
Have an idea but I am not sure how to go about it and if django alone would be enough?
I technically have 2 questions that I am combining into 1 post. In views we can run python stuff just as usual right? So how demanding a thing can I put in a view. Say I had some game made using pygame and PyOpenGL(3D). Can I put that in a view and expect it to work or do I need to do something additional to it because it is going to end up on a website and I need to know much I can stress django. The other part of the question is that, would it be dependent on the server django is being hosted on. Can I make it client sided (or is it so by default, knowing how powerful django is, I would expect it to be so). I know some part of this question is quite a bit 'noobish' but I am technically noob when it comes to django. All I have done is build one website with some forms and stuff (Basic beginner stuff). But now I am interested in stepping things up! The other thing is most of my projects and games that I run is on git hub and I have recently considered to β¦ -
how to check if the variable has a same value and return it as one value in python
I have four variables with in a defined function. def xyz(): a_1 = self.bal.getcod1() a_2 = self.bal.getcod2() a_3 = self.bal.getcod3() a_4 = self.bal.getcod4() i = getx(a_1) j = getx(a_2) k = getx(a_3) l = getx(a_4) val = i*j*k*l return val For eg : Based on the return value of getcod() i get 2,3,2,3 as a_1,a_2,a_3,a_4 respectively. I dont want duplicates to pass into the four variables i,j,k,l I want 2,3 to pass only once in two variables out of four variables and the rest should do nothing. If i have all 4,4,4,4 then only one time i need to pass it to one variable out of four variables and the rest should do nothing. If i have all 1,1,1,4 then i need 1,4 alone to pass it to two variables out of four variables and the rest should do nothing. so that i can avoid to return duplicate multiplied data in 'Val' variable. -
Failed to execute refresh metadata course in discovery service
I'm trying to install openedx in production environment: https://openedx.atlassian.net/wiki/spaces/OpenOPS/pages/146440579/Native+Open+edX+Ubuntu+16.04+64+bit+Installation Then I wanted to run the refresh refresh_course_metadata in discovery service with a production environment. I created an Oauth2 client in lms. I created a partner in discovery admin interface and I set the lms url and the client_id and the client sercret. When I executed the refresh course metadata command in discovery service I got the following error Traceback (most recent call last): File β/edx/app/discovery/discovery/course_discovery/apps/course_metadata/management/commands/refresh_course_metadata.pyβ, line 31, in execute_loader loader_class(*loader_args, loader_kwargs).ingest() File β/edx/app/discovery/discovery/course_discovery/apps/course_metadata/data_loaders/api.pyβ, line 82, in ingest response = self._make_request(initial_page) File β/edx/app/discovery/discovery/course_discovery/apps/course_metadata/data_loaders/api.pyβ, line 120, in _make_request return self.api_client.courses().get(page=page, page_size=self.PAGE_SIZE, username=self.username) File β/edx/app/discovery/venvs/discovery/lib/python3.5/site-packages/slumber/init.pyβ, line 155, in get resp = self._request(βGETβ, params=kwargs) File β/edx/app/discovery/venvs/discovery/lib/python3.5/site-packages/slumber/init.pyβ, line 103, in _request raise exceptions.HttpServerError(βServer Error %s: %sβ % (resp.status_code, url), response=resp, content=resp.content) slumber.exceptions.HttpServerError: Server Error 500: http://*********/api/courses/v1/courses/ In the lms logs I found: Traceback (most recent call last): File β/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/exception.pyβ, line 41, in inner response = get_response(request) File β/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.pyβ, line 249, in _legacy_get_response response = self._get_response(request) File β/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.pyβ, line 187, in _get_response response = self.process_exception_by_middleware(e, request) File β/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.pyβ, line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File β/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/utils/decorators.pyβ, line 185, in inner return func(*args, **kwargs) File β/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/views/decorators/csrf.pyβ, line 58, in wrapped_view return view_func(*args, **kwargs) File β¦ -
Class generic DeleteView not working for model related to model
I have a page containing assignment questions. Questions related to assignment is displayed on asisgnment details page with EDIT and DELETE anchor tags. But after pressing delete I get an error : Reverse for 'CreateQuestion' with arguments '('',)' not found. 1 pattern(s) tried: ['assignment/(?P[0-9]+)/createQuestion/$'] views.py class AssignmentDetailView(generic.DetailView): model = Assignment template_name = "dashboard/assignment_detail.html" class QuestionDeleteView(DeleteView): model = Question template_name = 'dashboard/assignment_detail.html' def get_success_url(self): return reverse_lazy('assignment_detail', kwargs={'pk': self.object.assignment_id}) urls.py path('<int:assignment_pk>/DeleteQuestion/<int:pk>/delete', views.QuestionDeleteView.as_view(), name='DeleteQuestion'), path('<int:pk>/createQuestion/', views.QuestionCreate, name='CreateQuestion'), path('assignment/<int:pk>', views.AssignmentDetailView.as_view(), name='assignment_detail'), assignment_detail.html <td> <a onclick="return confirm('Are you sure?');" href="{% url 'DeleteQuestion' assignment_pk=assignment.id pk=question.id %}">Delete</a></td> Models.py class Assignment(models.Model): number = models.IntegerField() course = models.ForeignKey(Course,on_delete = models.SET_NULL,blank=True,null=True) publish_date = models.DateField(auto_now_add = True) deadline_date = models.DateField() faculty = models.ForeignKey(Faculty,on_delete = models.SET_NULL,blank=True,null=True) def __str__(self): return f'Assignment {self.number}-{self.course}' def get_absolute_url(self): """Returns the url to access a detail record for this Assignment.""" return reverse('assignment-detail', args=[str(self.id)]) class Question(models.Model): assignment = models.ForeignKey(Assignment, on_delete=models.SET_NULL,blank=True,null=True) username = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True,null=True) title = models.CharField(max_length = 200) description = models.TextField(blank=True , null = True) marks = models.IntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): """Returns the url to access a detail record for this book.""" return reverse('question-detail', args=[str(self.id)]) -
Django views.py initalisation per session for external Databases
In Django I would like to access an external ArangoDB and do, after the initialisation some calculation with the data. This data-object should be kept alive during a session and will be accessed in several function calls of the views.py. I'm new to Django but I used to work with Java and Apache Tomcat, so I hope there are some parallels. From what I see there is no initialization or Session-Object in the views.py. Also I haven't really done much with the wsgi dev server and I'm not sure if it's the responsibility of the wsgi to do that (or how?) What would be a proper approach to initialize some objects per session within the views.py and what is necessary to keep them alive? -
when i converting second in minutes in django wy i getting error?
i try to convert second to minute but i am getting error def convert(seconds): seconds = seconds % (24 * 3600) hour = seconds // 3600 seconds %= 3600 minutes = seconds // 60 seconds %= 60 return "%dh:%02dm" % (hour, minutes ) Here i try to convert second to hour and minute def get_total_movingtime(self, obj): totalpieces = WorkDay.objects.filter().aggregate( total_movingtime=Round(Sum(convert('foot_time')))) return totalpieces["total_movingtime"] Error is "not all arguments converted during string formatting" How to resolve this Thanks -
Django struggling to get custom emails to work with activation link
My activation email sends, but there is no link to activate the email. I want to send a custom email with an activation link to activate a user's email. However, the link does not show up. from_email = 'mysite <info@domain>' htmly = get_template('activation_email_template.html') message = render_to_string('activation_email.html', { 'user':user, 'token':account_activation_token.make_token(user), 'uid':urlsafe_base64_encode(force_bytes(user.pk)), }) reverse( 'activate', kwargs={ 'token':force_text(urlsafe_base64_encode(force_bytes(user.pk))), 'uidb64':urlsafe_base64_encode(force_bytes(user.pk)) }) html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, message, from_email, [user.email]) msg.attach_alternative(html_content, "text/html") msg.send() Here are the templates for activation_email.html and activation_email_template.html: activation_email.html: {% autoescape off %} Hi {{ user.username }}, Email activation: http://domain{% url 'activate' uidb64=uid token=token %} {% endautoescape %} activation_email_template.html: this template includes all the custom formatting details <html> .... {% autoescape off %} <h3>Hi <strong>{{ username }}</strong>,</h3> <p>Email Activation</p> <a href="https://domain{% url 'activate' uidb64=uid token=token %}" style="..">Email Activation</a> {% endautoescape %} ... </html> -
How can I do to add two more entries just changing one parameter?
Hello I have these entries from the table informations : |name| city| birthplace|client| |peter| los angeles| new york|yes| |william| chicago| denver|yes| And I would like to do something like this : |name| city| birthplace|client| |peter| los angeles| new york|yes| |william| chicago| denver|yes| |peter| los angeles| new york|no| |william| chicago| denver|no| That is to say I would like to add the same lines but for the column client set no for the new lines. How can I do this using Django ? Here is my first line of this : info = informations.objects.filter(client='yes') and that last line returns this 2 entries. Thank you very much ! -
Django: How To Auto Fill all the Model form with the data on 'load' button click after accepting primary key as text input from the user
I am beginner in Django. I have a below requirement in Django Model Form while creating a new record with the submission Form to perform . 1.In form processing i want to auto fill all the form fields based on user primary key text input. 2.User text input from step1 is the primary key of already created record in MySQL DB, which is created before while processing POST request when user filled the form manually all the form fields and clicked on submit. Example: Assume the database has 10 records .Each record has some 12 fields. To create new record(11th record) ,we initially click on button:"AddGSP" which opens a form waiting for user input. 11th record to be created has only one field value to be changed from 5th record. Instead of manually typing all the fields i want to autofill all the formdata based on user textinput . As the user does not want to fill all the details present in the form, i created a input text with "load" button. If user enter:5 as text input and click on "load" button then the form should fill or (load) all the details same as 5th record from database and β¦ -
CORS and Session Auth issue while developing Vue.js app for Django API
Django API is running at https://app.company.com/api/. Nginx proxies all requests to Gunicorn socket. This API enforces session-based authentication, JWT is not an option. Login is handled by Django and resides at https://app.company.com/login/. I need to create Vue.js app for this API, to be accessible at https://app.company.com/gui/. This app does not need to perform login, it should rely on session cookie in browser memory. During development, the Vue app is served by vue-cli-3 development server on port 8080. My issues: API requests from Vue dev server (localhost) introduce CORS errors - different ports, different origin. Browser has the session cookie, but when I redirect to http://app.company.com:8080/gui (dev server), further API requests would NOT include session cookie. Later in production, the Vue app will be served the same way as Django API, by Nginx on port 443, so CORS and cookie should not be an issue, but how should I deal with this during development? I was considering to load Vue directly from CDN, in such case I could serve Vue app directly with Nginx even during development, but then I would miss webpack features. And if I am not mistaken, migrating to webpack at later stage is not that easy, or β¦ -
Django import-export on Ubuntu 16.04 raises JSON error
I am trying to upload a *.xslx file from django app to the model. Everything worked great until I deployed the app on a linux VM (Ubuntu 16.04). It raises the following error: the JSON object must be str, not 'bytes' This is the code from my views.py: if request.method == "POST": try: form = UploadFileForm(request.POST, request.FILES["excel_file"]) file = request.FILES['excel_file'] Import_Resource = resources.modelresource_factory(model=item)() dataset = tablib.Dataset() if not file.name.endswith('.xlsx'): messages.error(request, 'This is not a excel file!') imported_data = dataset.load(file.read()) I tried to decode the dataset object (as utf-8), but then I receive the error that it cannot decode character a certain position - guess this is because of some special latin charcaters which are in the content of the file I am trying to import. If I use latin-1 than it returns the following error: class 'KeyError'> 'p'. This is the reviewed code which generates the above error: def upload(request): if request.method == "POST": try: form = UploadFileForm(request.POST, request.FILES["excel_file"]) file = request.FILES['excel_file'] Import_Resource = resources.modelresource_factory(model=item)() dataset = tablib.Dataset() if not file.name.endswith('.xlsx'): messages.error(request, 'This is not a excel file!') imported_data = dataset.load(file.read().decode('latin-1')) Do you guys have any ideas on how could this issue be tackled? -
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 β¦