Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: NoReverseMatch at /patient/1/
I have this urls.py in cabinet app: urlpatterns = [ path('', views.index, name='index'), path('register_patient/', views.registerPatient,name='register_patient'), path('register_booking/', views.registerBooking,name='register_booking'), path('register_visit/<int:id>/', views.registerVisit,name='register_visit'), path('<int:id>/', views.detail_patient), ] before adding the 4th path('register_visit/<int:id>/'), the views.detail_patient was working well but now when I add this 4th path the views.detail_patient didn't work and I get this error: NoReverseMatch at /patient/1/ So my problem is that I can't use '<int:id>' more than one time and in my code I have the index page wich show the list of patients and every patient have a button 'details' who's will take me to the 5th path(('<int:id>/', views.detail_patient)) and in this template I have a button 'Nouvelle Chirurgie' who's gonna take me to the 4th path(('register_visit/<int:id>/', views.registerVisit,name='register_visit')). In index.html this the Details button: <a href="{{field.id}}/" class="btn btn-warning">Details</a> And in detail_patient.html this is the 'Nouvelle Chirurgie' button <a href="{% url 'register_visit' %}{{patients.id}}" class="btn btn-primary">Nouvelle Chirurgie</a> How to fix this error -
i want to edit admin panel ,which open with perticular staff user item list only and not want to compromise with TabularInline in same table
Hi i am trying to create rent and co living hobby project for that i want to use admin panel as staff dashboard where staff can perform CURD operations in this section there is on major condition staff can't edit each other property listing,and i have another table for property images where rent-property which i use in tabular inline .i am sharing screen shot below my admin.py code is given below from django.contrib import admin from .models import RentProperties,RentPropertyImages from django.utils.html import format_html from django.contrib.admin.widgets import AdminFileWidget from django.db import models # Register your models here. class RentPropertyImagesAdmin(AdminFileWidget): """Admin widget for showing clickable thumbnail of Image file fields""" def render(self, name, value, attrs=None, renderer=None): html = super().render(name, value, attrs, renderer) if value and getattr(value, 'url', None): html = format_html('<a href="{0}" target="_blank"><img src="{0}" alt="{1}" width="150" height="150" style="object-fit: contain;"/></a>', value.url, str(value)) + html return html class RentPropertyImagesInline(admin.TabularInline): model=RentPropertyImages formfield_overrides = {models.ImageField: {'widget': RentPropertyImagesAdmin}} fk_name="property_image" class ResntpropertiesAdmin(admin.ModelAdmin): inlines=[ RentPropertyImagesInline ] list_display=('posted_by','property_title','area','city','pincode','is_active') list_filter=('is_active','city','ac','childrens_play_area','club_house','fire_safety','is_flat_pg_flatmate') search_fields=('posted_by__username','city','area','pincode','state','property_code','property_title') exclude=('posted_by',) def save_model(self, request, obj, form, change): if not obj.posted_by: obj.posted_by = request.user obj.save() def has_add_permission(self, request, obj=None): if request.user.is_superuser: return True if obj is not None and obj.posted_by != request.user: return False return True def has_change_permission(self, request, obj=None): if … -
How do i deal with foreign key and multiple errors for Django API framework POST?
I have the following codes: models.py class Device(models.Model): hostname = models.CharField(max_length=50, unique = True) ipaddr = models.GenericIPAddressField(protocol='ipv4', unique=True, verbose_name='mangement IP') ##Use for mgt_id_addr date_added = models.DateTimeField(default=timezone.now) def __str__(self): return self.hostname class DeviceDetail(models.Model): SUBNET_CHOICES = ( ('16','16'), ('17', '17'), ('18','18'), ('19','19'), ('20','20'), ('21', '21'), ('22', '22'), ('23', '23'), ('24', '24'), ('25', '25'), ('26', '26'), ('27', '27'), ('28', '28'), ('29', '29'), ('30', '30'), ) DEV_MODS =( ('Catalyst 9606R', 'Catalyst 9606R'), ('C9300L-48T-4X', 'C9300L-48T-4X') ) mgt_interface = models.CharField(max_length=50) subnetmask = models.CharField(max_length=2, choices = SUBNET_CHOICES) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) dev_mod=models.CharField(max_length=50, choices = DEV_MODS) ##device_model replacement DD2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables def __str__(self): return self.hostname serializers.py from rest_framework import serializers from .models import Device, DeviceDetail class DeviceSerializers(serializers.ModelSerializer): class Meta: model=Device fields = '__all__' class DeviceDetailSerializers(serializers.ModelSerializer): class Meta: model = DeviceDetail fields = ['mgt_interface', 'subnetmask', 'ssh_id', 'ssh_pwd', 'enable_secret', 'dev_mod'] views.py @api_view(['POST']) def create_device(request): device = Device() devicedetail = DeviceDetail() deviceserializer = DeviceSerializers(device, data = request.data) devdserializer = DeviceDetailSerializers(devicedetail, data = request.data) if deviceserializer.is_valid() and devdserializer.is_valid(): deviceserializer.save() devdserializer.save(DD2DKEY=deviceserializer.id) results = { "device":deviceserializer.data, "device_details" : devdserializer.data, } return Response(results, status=status.HTTP_201_CREATED) else: errors = { "device":deviceserializer.errors, "device_details" : devdserializer.errors, } return Response(errors, status=status.HTTP_400_BAD_REQUEST) This statement devdserializer.save(DD2DKEY=deviceserializer.id) is giving me … -
How to get out of nested functions
I'm making chat bot service with Django. And my code invoke function in other function, to get the answer. My code is like this: def chat_view(request): user_input = request.GET.get('user_input') answer = flow(user_input) if len(answer) > 1: # Give the user a choice return HttpResponse(answer) def flow(user_input): data = get_data(user_input) # if len(data) > 1: # data_list = data # return data_list answer = get_answer(data) return answer def get_data(user_input): data = query_db_with_user_input(user_input) if len(data) > 1: # At this point, I want to give the user a choice to choose one data. # But to do that, I can pass it to the user after exiting the flow function. # So, I need to put ``if len(data) >1: something`` in the flow function and chat_view function. data_list = data return data_list return data def get_answer(data): answer = f'Data is {data}' return answer When the data is a certain condition, I want to escape all the nested functions and give a response to the user. However, if I write it as a comment, the code becomes too dirty and difficult to maintain. It doesn't matter if I have to rip and fix the code base. Does this have anything to do with … -
Different django url paths executing same view function
I am new to Django and working on to do app. I have following index.html, views.py and urls.py files in my Django app. Whenever I click on changes status link, still it is executing remove function from views.py. What's going wrong ? index.html <ol> {% for task in tasks%} <li> <div class="row"> <div class="col-4">{{task.id}}{{task.name}}</div> <div class="col-4"> <a href="{% url 'to_do_app:change_status' task.id %}"> {% if task.status %} <i class="fas fa-check-circle"></i> {% else %} <i class="far fa-circle"></i> {% endif %} </a> </div> <div class="col-4"><a href="{% url 'to_do_app:remove' task.id %}"><i class="far fa-2x fa-trash-alt"></i></a></div> </div> </li> {% empty %} <li>No Tasks</li> {% endfor %} Views.py date = datetime.datetime.now() def index(request): tasks = Task.objects.all() return render(request, "to_do_app/index.html", { # pass the list of tasks for this perticular session "tasks": tasks, "date": date }) def add(request): # Server Side Form data validation form = NewTaskForm() if request.method == "POST": # take all the data posted from frontend via post request and store it variable 'form' form = NewTaskForm(request.POST) # check if data is valid or not if form.is_valid(): # clean the data task = form.cleaned_data['name'] # append list Task(name=task, status=True).save() # after New task is added, redirect to index page # reverse() function figures out the … -
I am having trouble on fetching data from graphql using apollo and router. Backend: Django, frontend vue
Please find the browser console error Hi evryone, I managed to go through all steps in realpython tutorial to build a blog using django, vue and graphql. My django and vue applications works fine. However, on step 8 (the last step of the tutorial), trying to fetch the data using graphql api is not working. I configured the right end point for apollo. I built a query for all components as provided in the tutorial. At the end nothing is displayed. It is just same as step 7. Has anyone had an experience with this or have some input on what the best option is? -
Data is not saved while using FIlteredSelectMultiple widget
forms.py class RegistrationCreateForm(forms.Form): player = forms.ModelChoiceField(queryset=Player.objects.all(), widget=FilteredSelectMultiple("Player", is_stacked=False)) def __init__(self, *args, **kwargs): super().__init__() class Meta: model = Registration fields = ['player'] @property def media(self): w1 = FilteredSelectMultiple("", False) form_media = forms.Media(js=['js/jsi18n.js'], css={'all': ['css/filtered.css']}) return (w1.media + form_media ) views.py class RegistrationCreateView(AccessControlMixin, CreateView): model = Registration form_class = RegistrationCreateForm template_name_suffix = '_create' def has_access(self, user): return self.can("create_registration", self.tournament) def get_success_url(self): return "%s" % reverse("tournaments:detail", kwargs={"pk": self.kwargs['pk']}) def dispatch(self, request, *args, **kwargs): """ Overridden so we can make sure the `Tournament` instance exists before going any further. """ self.tournament = get_object_or_404(Tournament, pk=kwargs['pk']) return super(RegistrationCreateView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): self.tournament = get_object_or_404(Tournament, pk=self.kwargs['pk']) context = super(RegistrationCreateView, self).get_context_data(**kwargs) context['tournament'] = self.tournament return context def form_valid(self, form): form.instance.tournament = self.tournament form.instance.created_by = get_request().user player_institution_relation = PlayerInstitution.objects.filter(Q(player= form.instance.player) & Q(institution = self.tournament.owner)) if player_institution_relation.exists(): number_of_objects = player_institution_relation.count() if number_of_objects>1: for player_inst in player_institution_relation[1:]: player_inst.delete() else: PlayerInstitution.objects.create(player=form.instance.player, institution=self.tournament.owner) return super(RegistrationCreateView, self).form_valid(form) def get_form(self, *args, **kwargs): tournament = get_object_or_404(Tournament, pk=self.kwargs['pk']) form = super(RegistrationCreateView, self).get_form(*args, **kwargs) #Remove any player that has already a registration if get_request().user.name_format == 'First name Last name': form.fields['player'].queryset = tournament.available_players.order_by("first_name","last_name") else: form.fields['player'].queryset = tournament.available_players.order_by("last_name","first_name") return form I am using FilteredSelectMultiple widget for a foreign key field. It is rendering the form as i … -
How to make excel download function in python
The code below is a function to download a table as an Excel file. Table is being merged using DataTable jquery. The problem with the code below is that only two rows are compared and merged. I want to merge the whole data. Please help. The reason that 'register_date_str' is printed twice in values_list is because in the case of values_list, student[0] cannot be used twice. In this case, the value is not output when downloading Excel. What's the best way to use Excel without printing the same value to valuse_list twice? worksheet.write(row, col, str(student[2]) + '-' + str(student[3])) -> Only the 'name' value is printed, not combining two values in one cell. Why? def download_excel: output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() d_format = '%Y-%m-%d' border_center = workbook.add_format({'align': 'center', 'border': 1, 'bold': 1}) bold = workbook.add_format({'bold': True, 'border': 1, 'align': 'center', 'valign': 'vcenter', 'text_wrap': True}) student_header = [["weekday name", 5], ["register_date", 10], ["name - sex", 30], ["phone_number", 15], ["class_name", 15], ["teacher", 15]] row = 0 col = 0 for a_header, width in student_header: worksheet.write(row, col, a_header, border_center) if width is not None: worksheet.set_column(col, col, width) col += 1 students = Student.objects.filter(is_deleted=False).order_by('register_date') \ .annotate(register_date_str=Cast('register_date', CharField())) \ .values_list('register_date_str', 'register_date_str', … -
how you can handle 2 different types of arguments with only one view in django rest framework?
I have urls.py looks like below urlpatterns = [ path("watch-list/<int:pk>/", views.WatchItemDetail.as_view(), name="watch-detail"), path("watch-list/<str:slug>/", views.WatchItemDetail.as_view(), name="watch-detail-slug"), ] so i am sending 2 different type of arguments in same path one is pk and it can also be slug. In my views.py I am writing 2 get request I know this will not work since python not support overloding of methods so how can i achieve like below logic? can we clean up some code also because i am repeating my self with same logic. class WatchItemDetail(APIView): def get(self, request, pk): watch_item = get_object_or_404(WatchItem, pk=pk) watch_item_serializer = WatchItemSerializer(watch_item) return Response(watch_item_serializer.data, status=status.HTTP_200_OK) def get(self, request, slug): watch_item = get_object_or_404(WatchItem, slug=slug) watch_item_serializer = WatchItemSerializer(watch_item) return Response(watch_item_serializer.data, status=status.HTTP_200_OK) This will work only for slug field because previous method is overwritten by next one but i want both of them to work. -
How do I add an API key I already have to Django?
I am working on an REST API assignment, and I have completed it in Django. The last thing I need to do is to implement the authentication, in terms of keys. The project documentation has already given me a key I need to use, I cannot use the key generated by Django. How do I input that key as one of the authorized keys for the Django project? I have already installed the API key framework for Django from this documentation. -
How to sort using string like 'last name' in django queryset
I want to sort Groups with their 'is_favorite' boolean field from model GroupUser. I have two models GroupUser where there is a foreign key to Group model, now when I query Group.objects.filter(is_active=True).order_by('groupuser__group_id__is_favorite') I get groups multiple times. I tried to user distict() on final queryset still no luck. Pls suggest any other way or possible solution. TIA. -
@page :left and @page :left Not working in Django and xhtml2pdf library
Getting Error while applying @page:left{}.. How to solve this error. I searched on google but not get any solution. **page = page + '_' + pseudopage TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'** -
The usage of {% url ...%} vs {{ ... }} in Django templates
I've been practicing Djnago and for that, I was building a blog. While in the process of building it, I was faced with an error, while using the following code: <a href="{% url 'blog_post' post.slug %}"> {{ post.title }} </a> While studying and doing other courses something like this would work fine. But now, it will raise this exception: NoReverseMatch. If I use this code though, it will work just fine: <a href="{{ post.slug }}"> {{ post.title }} </a> While working in different projects the first way would work fine, but this time, it doesn't. My question is why? Here is the code in my urls and on my views. Maybe the mistake is here, not somewhere else. If anyone can explain why this is happening, or where I'm going wrong, it will be greatly appreciated urls: from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.blog_index, name='blog_index'), path('<slug:post_slug>/', views.blog_post, name='blog_post'), ] views: from django.shortcuts import render from .models import Post # Create your views here. def blog_index(request): posts = Post.objects.order_by('- created').filter(published=True) data = { 'posts': posts } return render(request, 'blog/post_list.html', data) def blog_post(request, post_slug): post = Post.objects.get(slug=post_slug) data = { 'post': post } … -
Upload excel in django and display in 4 different webpages
I want to upload an excel file containing 4 columns and display each column in different page. views.py def upload(request): if "GET" == request.method: return render(request, 'myapp/upload.html', {}) else: excel_file = 'WBSdetails.xlsx' pd.read_excel(excel_file, sheet_name = 'ItemDetails') return render(request, 'myapp/structuremaster.html') def structure(request): structures=ConVehicleMaster.objects.all() context={ 'structures':structures } return render(request, 'myapp/structuremaster.html', context) models.py class Excel(models.Model): structure = models.CharField(("Structure"), max_length=150) segment = models.CharField(("Segment"), max_length=150) subsegment = models.CharField(("SubSegment"), max_length=150) element = models.CharField(("Element"), max_length=150) structuremaster.html <tbody> {% for row in WBSdetails %} {% for cell in row %} <tr> <td>{{ cell.structure }}</td> </tr> {% endfor %} {% endfor %} </tbody> I am new to django and have very little idea. Any help will be appreciated. -
Django - method not allowed error after moving ajax request to different app
I have a small form in my django app called home that I submit through jquery ajax request. Below is the setup that I have home urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^submitseries/$', views.submitseries, name='submitseries'), url(r'^getstats/$', views.getstats, name='getstats'), ] home views.py def submitseries(request,id=None): if request.method == "POST": series_url = request.POST.get("series_url") # rest of the processing code that is working fine application urls.py from django.contrib import admin from django.urls import include,path urlpatterns = [ path('', include(('home.urls','home'),namespace="home")), path('series/', include(('series.urls','series'),namespace="series")), path('submitseries/', include(('home.urls','submitseries'),namespace="submitseries")), path('players/', include(('players.urls','players'),namespace="players")), path('admin/', admin.site.urls), ] This setup is working fine but I would like to move this ajax request to a different app in my application that is with name series So I have moved the submitseries function to views.py of series app modified the series urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^$submitseries/', views.submitseries, name='submitseries'), ] ((tried different variations such as series/submitseries/ )) modified the application urls.py as following from django.contrib import admin from django.urls import include,path urlpatterns = [ path('', include(('home.urls','home'),namespace="home")), path('series/', include(('series.urls','series'),namespace="series")), path('submitseries/', include(('series.urls','submitseries'),namespace="submitseries")), path('players/', include(('players.urls','players'),namespace="players")), path('admin/', admin.site.urls), ] rather than pointing it to home.urls I have pointed it to series.url … -
How to send google calendar data to full Calendar in django?
I want to send all google calendar events to full Calendar in django. I have accessed the all events in google calendar of user after they login. Now I have to send these details to full Calendar. def connect_google_api(): creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json') if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file('credentials2.json',SCOPES) creds = flow.run_local_server(port=0) with open('token.json','w') as token: token.write(creds.to_json()) service = build('calendar','v3',credentials=creds) now = datetime.datetime.utcnow().isoformat()+'Z' page_token = None calendar_ids = [] while True: calendar_list = service.calendarList().list(pageToken=page_token).execute() for calendar_list_entry in calendar_list['items']: if "myorganisation" in calendar_list_entry['id']: calendar_ids.append(calendar_list_entry['id']) page_token = calendar_list.get('nextPageToken') if not page_token: break print(calendar_ids) for calendar_id in calendar_ids: count = 0 print(calendar_id) eventsResult = service.events().list( calendarId = calendar_id, timeMin = now, maxResults = 5, singleEvents = True, orderBy = 'startTime').execute() events = eventsResult.get('items',[]) response = JsonResponse(events,safe=False) if not events: print('No upcoming events found') print(events) print("-----------------------------------") I am trying to understand this documentation. It is asking me to provide CalendarId look like abcd1234@group.calendar.google.com. I am printing events in my code and I could not find anything in the format of abcd1234@group.calendar.google.com. print(events) gives some thing like this {kind:calendar#event,'etag': '"381732929101038"', 'id': 'someid', 'status': 'confirmed', 'htmlLink': 'https://www.google.com/calendar/event?eid=', 'created': '', 'updated': '', … -
Reverse for 'new_project' with arguments '('',)' not found. 1 pattern(s) tried: ['new_project/$']
I have just learned to use python and Django for 2 weeks, and I'm trying to build a to-do list. I encountered an error and I might need some advice on it. In the to-do list, there is a page for all projects, and when u click into a project there will be a to-do list. I tried to achieve add a new project function by these codes, but it returns the error as shown in the title, I've been looking into many answers online, most of the reason that caused the issue was because of the inappropriate introduction of URL in HTML file or when u specified more values than form in views.py and u forgot to place them behind url. I still can't understand the error, I would really appreciate it if u could give me some hints on where I might get wrong. Thanks urls.py app_name = 'todo_lists' urlpatterns = [ # homepage path('', views.index, name='index'), # page that shows all projects path('projects/', views.projects, name='projects'), # details of a project path('projects/<int:project_id>/', views.project, name='project'), # add a new project path('new_project/', views.new_project, name='new_project'), views.py def new_project(request): # add new project if request.method != 'POST': # if not submit then … -
Activate venv in vs code
I have been trying to activate a virtual environment using Python's built-in module venv from VS Code without unfortunately any success. I don't get any error message, it simply won't activate. However, If I run the venv\Scripts\activate.bat command from the terminal it don't works ... -
Django-wanted to run the time continuously without refreshing the page
I have developed an Django application where it will take the time based on the timezone and it's working properly but when i refresh the page the time change how could I do without refreshing the page.Even i have no idea to implement it in js or ajax.If anyknow how could be possible to implement django code with the js or ajax. single.html {% extends 'base.html' %} {% block content %} <div class="container-md" id='firstcontainer'> <form action="" method="POST" autocomplete="off"> {% csrf_token %} <div class="container-md"> <h3 id ='user'>Search</h3> <div class="row"> <div class="input-group" > <div class="col-md" > <input class="form-control" type="search" placeholder="Search" id='btnsearch' name="finder" > <br> </div> <div class="pull-left"> <button class="btn btn-outline-success" style="width:70px;height:46px;" type="submit" >Search</button> </div> </div> {% if finder %} {% for list in userb %} <h3>User List</h3> <table class="table table-striped table-hover"> <tr> <!-- <th scope="col">ID</th> --> <td><b> Username </b></td> <td>{{list.username }}</td> </tr> <tr> <td> <b>Email</b></td> <td>{{list.email }}</td> </tr> <!-- <th scope="col"> Format</th> --> <tr> <td><b>Time</b></td> <td id='mydate'> {{mydate}}</td> </tr> <!-- <div class="col"> DateTime</div> --> <!-- <th scope="col">TimeZone</th> --> <!-- <th scope="col">Action</th> --> <!-- <th scope="row">{{list.id}}</th> --> <!-- <td>{{list.username }}</td> --> <!-- <td>{{list.email }}</td> --> <!-- for only the date time --> <!-- <div class="col"> {{my_date}}</div> --> <!-- <div class = 'col'>{{my_date}}</div> --> … -
Unable to update post using models in django
I want to prepare a webpage which outputs book name, publisher and author and want to add the data dynamically using admin panel but unable to do it using below code. Please help models.py from django.db import models class researchpaper(models.Model): title = models.CharField(max_length=200) publication = models.CharField(max_length=200) authors = models.CharField(max_length=200) def __str__(self) -> str: return self.title views.py def publications(request): context = { 'researchposts': researchpaper.objects.all() } return render(request, 'lab/publications.html',context) urls.py path('publications', views.publications, name='publications'), html file {% for paper in object_list %} <tr> <td> <h5>2021</h5> <p style="color: black;"><b>{{paper.title}}1. A minimal model for synaptic integration in simple neurons</b></p> <p style="font-size: 14px;"><i>Physica D: Nonlinear Phenomena, 2021</i></p> <p style="font-size: 14px;"><i>Adrian Alva, Harjinder Singh.</i></p> </td> <td><a href="#" target="blank" style="color: dodgerblue;"><i class="ai ai-google-scholar-square ai-2x" style="padding-right: 10px;"></i></a></td> </tr> <tr> <td> <hr> </td> </tr> {% endfor %} -
Input for field is missing even after i type the correct format on the API
I have coded the following: models.py class Job(models.Model): datetime = models.DateTimeField(default=timezone.now) combinedparameters = models.CharField(max_length = 1000) serializers.py class JobSerializers(serializers.ModelSerializer): class Meta: model = Job fields = ['combinedparameters'] views.py @api_view(['POST']) def create_job(request): job = Job() jobserializer = JobSerializers(job, data = request.data) if jobserializer.is_valid(): jobserializer.save() return Response(jobserializer.data, status=status.HTTP_201_CREATED) return Response(jobserializer.errors, status=status.HTTP_400_BAD_REQUEST) Page looks like this: But if i copy {'device': 177, 'configuration': {'port_range': 'TenGigabitEthernet1/0/1,TenGigabitEthernet1/0/2,TenGigabitEthernet1/0/3,TenGigabitEthernet1/0/4,TenGigabitEthernet1/0/5', 'port_mode': 'Access', 'port_status': 'Disabled', 'port_param1': 'Test\\n1\\n2\\n3', 'port_param2': 'Test\\n1\\n2\\n3'}} And click post, got error saying the single quotes have to be double quotes. So i changed it to : {"device": 177, "configuration": {"port_range": "TenGigabitEthernet1/0/1,TenGigabitEthernet1/0/5", "port_mode": "Access", "port_status": "Disabled", "port_param1": "1\\n2\\n3", "port_param2": "1\\n2\\n3"}} I clicked post again and this time the following error comes out: I dont understand why is it happening. The reason why I key in the long format because this is the format i want to save in my database and this format is created upon saving from my html that creates the job -
Grouping imports together from subdirectories
Say I have a django app where I'm using folders and subfolders to organize my models: app models __init__.py accounts user.py profile.py social facebook.py twitter.py linkedin.py admin.py apps.py urls.py views.py My __init__.py file is as follows: from .accounts.user import User from .accounts.profile import Profile from .social.facebook import Facebook from .social.twitter import Twitter from .social.linkedin import LinkedIn Is there any way to group these imports together or make the code shorter? E.g. (obviously doesn't work) from . import * # or from .accounts import * from .social import * -
Trouble ussing Buddy to test a project using Django REST FRAMEWORK POSTGRE AS DB
Hello I'm currently trying to implement Buddy with my little StartUp that is using DJANGO REST FRAMEWORK as a base. I found a very good example on the site. Unfortunately in the exmaple the used a MySql DB and I'm using Postgre as DB. My settings.py is: # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DBname', 'USER': 'DBuser', 'PASSWORD': 'DBpassword', 'HOST': '', 'PORT': '5432', } } } My Buddy execute look somethig like this: pip install -r requirements.txt cd Project python manage.py test I also created postgre service in Buddy like version: latest, Hostname: postgres, Port:5432, Login:DBuser, Password:DBpassword, Name of a database to be created on container startup: DBname When I run the build Test of my project an error message apears like this: connection = Database.connect(**conn_params) File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? Action failed: see logs above for details I really don't now how to fix this, it appears that Buddy creates the database correctly but for some reason django does not reconise that it exists. -
Django Data Migrations: Table Doesn't Exist
I am running into the issue described here: Django: Providing initial group with migrations Specifically, I'm working on legacy code which initialized a 'Countries' table from an init_data file. I now need to add countries (e.g. South Sudan). My understanding is that I should use migrations to add this data, so that the prod database and the test machines will be in sync. Here is my attempted migration: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def forwards_func(apps, schema_editor): Country = apps.get_model('countries', 'Country') db_alias = schema_editor.connection.alias Country.objects.using(db_alias).update_or_create(iso='SS', defaults={'name': 'SOUTH SUDAN', 'printable_name': 'South Sudan', 'iso3': 'SSD', 'numcode': 728}) def reverse_func(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('countries', '__latest__'), ] operations = [ migrations.RunPython(forwards_func, reverse_func) ] The new migrations works on an existing database, but when the test pipeline spins up a fresh machine, it fails with django.db.utils.ProgrammingError: (1146, "Table 'test_cc_dev.country' doesn't exist") I understand from the above link that the problem stems from all of the migrations needing to run as a group. I do not understand the solution. Am I supposed to add the whole table again in this migration? The original data was loaded in the 0001_initial.py file like this: def forwards_func(apps, schema_editor): … -
How to make simple drag&drop in django?
So, I have a django website that do some pandas calculations, it takes excel file and do calculations and returns file. So, I'm trying to make work this drag&drop but it's not working. I get this in my view, will not forward file and not looking right. cal.py def OnlyCAL(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] #pandas calculations response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response else: form = DocumentForm() return render(request, 'cal.html', { 'form': form, 'page_title':page_title }) cal.html {% extends "base.html" %} {% load static %} {% block content %} <style type="text/css"> .box__dragndrop, .box__uploading, .box__success, .box__error { display: none; } .box.is-dragover { background-color: grey; } </style> <form class="box" method="post" action="{% url "rec" %}" enctype="multipart/form-data"> {% csrf_token %} <div class="box__input"> <input class="box__file" type="file" name="files[]" id="file" data-multiple-caption="{count} files selected" multiple /> <label for="file"><strong>Choose a file</strong><span class="box__dragndrop"> or drag it here</span>.</label> <button class="box__button" type="submit">Upload</button> </div> <div class="box__uploading">Uploading…</div> <div class="box__success">Done!</div> <div class="box__error">Error! <span></span>.</div> </form> <script> if (isAdvancedUpload) { var droppedFiles = false; $form.on('drag dragstart dragend dragover dragenter dragleave drop', function(e) { e.preventDefault(); e.stopPropagation(); }) .on('dragover dragenter', function() { $form.addClass('is-dragover'); }) .on('dragleave dragend drop', function() { $form.removeClass('is-dragover'); }) .on('drop', …