Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django user_groups table missing
I ahve a user model called TbUser and I have integrated a mysql legacy database with django. After doing migrations I have the follwing tables. django_seesion, django_migrations, django_content_type, django_admin_log, auth_permission, auth_group_permissions, auth_group When I log in to django admin page, and click on the TbUser then select a random user I am getting the following error. Exception Value: (1146, "Table 'db.tb_user_groups' doesn't exist") Should this table be created when migrations are run? -
SolarWinds N-central 5000 Query failed using zeep
I am trying to add Customer using zeep in Python3 in N-central Solarwind and getting error 5000 Query failed. def addcustomer(request): client = Client('http://server-name.com/dms/services/ServerEI?wsdl') settings_type=client.get_type('ns0:T_KeyPair') value = settings_type( 'customer_name','id_' ) response =client.service.CustomerAdd(Username=USER,Password=PASS, Settings=value) return render(request,'ncentral/addcustomer.html',locals()) This is what is written in Docs int customerAdd(String username, String password, List settings) throws RemoteException Adds a new Customer or Site to the MSP N-central. Parameters: username - the MSP N-central username. password - the Corresponding MSP N-central password. settings - A list of settings stored in a List of EiKeyValue objects. Below is a list of the acceptable keys and values. Mandatory (Key) customername - (Value) Desired name for the new customer or site. Maximum of 120 characters. Mandatory (Key) parentid - (Value) the (customer) id of the parent service organization or parent customer for the new customer/site. (Key) zip/postalcode - (Value) Customer's zip/ postal code. (Key) street1 - (Value) Address line 1 for the customer. Maximum of 100 characters. (Key) street2 - (Value) Address line 2 for the customer. Maximum of 100 characters. (Key) city - (Value) Customer's city. (Key) state/province - (Value) Customer's state/ province. (Key) telephone - (Value) Phone number of the customer. (Key) country - (Value) Customer's country. Two … -
Bulk create or update objects in database model in Django based on excel file
So I have following excel file: CustomerName ChannelName MarketName Cust-1 Chan-2 Market-1 Cust-1 Chan-2 Market-1 Cust-1 Chan-2 Market-1 Cust-1 Chan-3 Market-4 Cust-1 Chan-2 Market-5 Cust-2 Chan-2 Market-6 Cust-1 Chan-1 Market-7 Cust-1 Chan-2 Market-8 Cust-2 Chan-3 Market-9 Cust-3 Chan-4 Market-10 Which I load to dataframe using Pandas and then I iterate over rows to save every unique customer name market and channel combination I have in this file to my database.Which means that of the first 3 rows in the example only one object should be created since they are all the same. My customer model in Django is the following: class Customer(models.Model): """ Stores a single customer, related to :model:`customers.Market` and :model:`customers.Channel` and :model:`warehouses.Warehouse` """ market = models.ForeignKey(to="Market", default=None, on_delete=models.CASCADE, verbose_name="Market", help_text="Market id") channel = models.ForeignKey(to="Channel", default=None, on_delete=models.CASCADE, verbose_name="Channel", help_text="Channel id") name = models.CharField(max_length=128, default=None, verbose_name="Customer Name", help_text="Customer Name") def __str__(self): return self.name And this is how I am saving objects to the database pased on this dataframe: def transform_df_to_clientmodel(df): """Save all unique customers to database""" df.apply(lambda row: bulk_iterator_customer(row), axis=1) def bulk_iterator_customer(row): """ Create object in customer model Fetches object from database if exist and update with fields passed in defaults dict otherwise create new """ models.Customer.objects.update_or_create( name=row["CustomerName"], channel=models.Channel.objects.get(name=row["ChannelName"]), market=models.Market.objects.get(name=row["MarketName"]) … -
Managing migration of large number of fixtures in Django for unit testing
I currently have one fixtures for all my tests for my Django application. It is fine however updating units tests each time I add new object to my fixture is tedious. Objects count and equality of query set have to be updated. Many "get" method fails when duplicate appears for various reasons. Having a dataset filled with every possible use-case for each unit test seems like a bad practice. So I would like to have a fixture for each component of the app to test, e.g. if I have a model class "MyModel", it have a dedicated TestCase all its functionalities have unit tests and i would like them to have a dedicated fixture. The main interest would be that I automatically solves all three points mentioned above. However it has some drawbacks File management, I copy a directory into django's data directory for my fixture, I would need to manage multiple data directory. Redundance of some fixtures elements. Many element relies on the existence of other elements up to the user object, each fixture would need a prefilled database with some common objects (e.g. configured user) Django migrations. The two first points are not real problem but the task … -
django write dict to json and return json file object
I have some queryset from which I have to create json file and return file object as a response but while doing so I am getting server error. result = {'name': 'Test sample'} f = open("sample.json", "w") f.write(json.dumps(result)) f.close() return FileResponse(f, as_attachment=True, filename='sample.json') I think it should return json file object but it is not doing so. Its saying A server error occurred. Please contact the administrator. What am I missing here ? -
Django filter by date range and if no records in a date, return dummy records in that without being dead in loop
I have a very unique requirement and I have not noticed such a solution on Django documentation. Also, I don't want to use any loop after the database query even though I can achieve such a solution with loop over all the records. class Example(models.Model): date = DateField name = CharField and Let's say i have following records in the table [ {date: "2018-01-05", name="jhon doe"}, {date: "2018-01-11", name="jonathan someone"}, {date: "2018-01-21", name="someone developer"}, ] and my query: Example.objects.filter(date_range=["2018-01-01", "2018-01-31"]) As normal when we query with a date range, it returns all the records within that range. it's expected and normal. But I want it should come with a blank record when there are no records on a certain date range. As we notice I have only 3 records in that range, so I am expecting a result like this [ {date: "2018-01-01", name="Not Found"}, {date: "2018-01-02", name="Not Found"}, {date: "2018-01-03", name="Not Found"}, {date: "2018-01-04", name="Not Found"}, {date: "2018-01-05", name="jhon doe"}, {date: "2018-01-06", name="Not found"}, '''''to be continued in a range'''' ] Is there anyone who knows to prepare queryset like above this during filter? I need it like this coz, i am using a javascript tool in the frontend, … -
using __in operator in if condition
I have view with if condition: if request_status.id__in [3,5]: car.booked = False car.save() I want to use __in operator in it similar to this example Entry.objects.filter(id__in=[1, 3, 4]) Any help is appreciated. -
How to automatically add logged in user as creator of product
I have a form that can create a product. My problem is how do I add the logged-in user automatically? While logged-in, when I create a product and look at admin http://127.0.0.1:8000/admin the 'creator' object is blank --- or I have to choose the user manually. I want to relate a product with a user. models.py from django.db import models from django.contrib.auth.models import User class Product(models.Model): creator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) prodname = models.CharField(max_length=255, null=True) description = models.CharField(max_length=255, null=True) price = models.FloatField(null=True) image = models.ImageField(null=True, upload_to='images') views.py from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login, logout from .forms import ProductForm, RegisterUserForm from .models import * def home_view(request): return render(request, 'home.html') def product_create_view(request): form = ProductForm() if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() context = { 'form':form } return render(request, 'product/product_create.html', context ) def register_view(request): form = RegisterUserForm() if request.method == 'POST': form = RegisterUserForm(request.POST) if form.is_valid(): form.save() return redirect('product/login.html') context = { 'form': form } return render(request,'product/register.html', context) def login_user(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home-view') else: messages.info(request,'Username or password is incorrect') return render(request,'product/login.html') def logout_user(request): logout(request) … -
Do I define new models if they already exist in db? [duplicate]
I am new to Django. I am trying to write a code, which takes data from a database and shows it in a website. My question is, if the data already exist in the database and I only want to get them, do I need to define new models in the models.py? -
How to store model field data type based on choices?
Here in my model I want to set option value based on choice value. How can I do this or any other solutions ? class MyModel(models.Model): title = models.ForeignKey(Title, on_delete=models.CASCADE) option_name = models.CharField(max_length=200) option_value_choices = [ (1, "models.BooleanField"), (2, "models.DateField"), (3, "models.IntegerField"), (4, "models.CharFIeld") ] option_value_type = models.CharField(max_length=10, choices=opt_choices) option_value = .. ? -
how to make a field have choices from another model in django
I am creating a gradeviewing app for my School Project and I am confused on how do I need to build relationships of each models. I want a subject field on my StudentGrade model to have a list of choices coming from Student model but I only want to display/get the enrolled_subjects of the student instance model.py: class Subjects(models.Model): subject_name = models.CharField(...) subject_code = ... ... class Student(models.Model): student = models.ForeignKey(setttings.AUTH_USER_MODEL,...) enrolled_subjects = models.ManyToManyField(Subjects) ... class StudentGrade(models.Model): PERIOD_CHOICES = [ ... ] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, limit_choices_to=Q(is_student=True)) period = models.CharField(choices=PERIOD_CHOICES, max_length=25) subject = // i want this to be list of subjects that the student has enrolled grade = models.DecimalField(max_digits=4, decimal_places=2) on the StudentGrade model, I want the subject field to be based on the enrolled_subjects of student instance how can I do that? -
How to update model except null values using PUT method in django?
I have a Post model which has many fields. I want to update a field only if it's not null which means it should have the value from the request. post = PostModel.objects.get(id = id).update() -
How do you create a dynamic form field in Django?
I want to create a dynamic form field that always filters a model and shows the filtered elements in a list in the form. Here is the code I have so far: class OrganisorClassStatusUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrganisorClassStatusUpdateForm, self).__init__(*args, **kwargs) self.fields['off_day_student'] = forms.ModelChoiceField( queryset=Class.objects.filter(teacher=self.object.teacher).filter(is_new_set=True).filter(time=self.object.time).order_by('-date')[:10] ) The problem I have with this code is that the self.object refers to the form itself, not the model I am trying to update. This is important since I need to filter the queryset using some of the information in the model I am trying to update. Please ask me any question if you need anything. Thanks a lot. -
Validating a Regex pattern entered into form via user interface
I'm struggling to find how to validate a user entered Regex pattern. The use case here is that the user interfaces allows the user to create rules that merge any incoming Merchants that meet the regex pattern specified in a rule. So the user themselves enter the regex pattern. I hope that makes sense. merchants = Merchant.objects.filter(name__iregex=merge_rule.pattern) I get system errors when a bad regex is entered into the rule, so I'd like to validate against these. -
How do I connect to an mssql db that is on a windows computer from a linux VM inside these computers' intranet?
I have a client that has a desktop application for its employees. I've been tasked with porting this over to a web application that runs within their intranet. This web application obviously needs to connect to the db they currently have. But I am lost as to how to do this. It's an mssql db. I've never worked with mssql before. Nor have I made a web application that runs only within an intranet. Can anyone help? I'm writing this web app in django, for what it's worth -
How to POST multiple objects in one JSON request?
I am using django-rest-framework and recently I encountered a problem. I need to post such request and get 2 objects created: { "lease": 28, "date": [ { "from_date": "2021-06-01", "until_date": "2021-07-01" }, { "from_date": "2022-03-22", "until_date": "2022-04-23" } ] } Model looks like this: class DateUnavailable(models.Model): lease = models.ForeignKey(Lease, on_delete=models.CASCADE, blank=False, null=False) from_date = models.DateField(blank=True, null=True) until_date = models.DateField(blank=True, null=True) Currently my views.py looks like this: class DateUnavailableCreateView(generics.CreateAPIView): #POST permission_classes = [IsAuthenticated, ] def get(self, request): all_dates = DateUnavailable.objects.all() serializer = DateUnavailableSerializer(all_dates, many=True) return JsonResponse(serializer.data, safe=False) def post(self, request, *args, **kwargs): lease = request.data['lease'] dates = dict(request.data.items())['date'] flag = 1 arr = [] for date in dates: modified_data = modify_input_for_multiple_dates(lease, date) date_serializer = DateUnavailableSerializer(data=modified_data, many=True) if date_serializer.is_valid(): if date_serializer.validated_data["lease"].user != self.request.user: return (Response('You are not allowed to make changes to this schedule', status=status.HTTP_405_METHOD_NOT_ALLOWED)) date_serializer.save() arr.append(date_serializer.data) else: flag = 0 return (Response(arr, status=status.HTTP_201_CREATED) if flag == 1 else Response(arr, status=status.HTTP_400_BAD_REQUEST)) This view is the slight modification of the one that I used successfully for creating multiple file objects related to one object through ForeignKey. -
Django Accessing Child Data in Templates from Parent object
I am new to Django and am trying to do something that should be very straightforward (in my mind) but I've spent a few hours on this and haven't solved it yet. Goal: Within a template I would like to get a value from a field from a child object using the parent. In this case I am trying to get the lab_request object by knowing the parent sample. So far I have tried using both a ForeignKey in the Lab_Request model as well as a OneToOneField Specific area in the code where I believe I am going wrong is {{ sample.lab_request.placeholder_to_be_replaced }}. Sample is a parent and 'Lab_Requests' is a child. In thus case I have set it to OneToOneField but really I have this issue in another area where it will be a Parent to multiple Children. Code: #models.py class Sample(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) status = models.CharField(max_length=2, choices=SAMPLE_STATUS_OPTIONS, default="01") sample_number = models.CharField(max_length=19, unique=True, editable=False, default=get_sample_number) class Inspection_Request(models.Model): #Add stuff here placeholder_to_be_replaced = models.CharField(max_length=1) sample = models.OneToOneField(Sample, on_delete=models.CASCADE) inspector = models.OneToOneField(Inspector, on_delete=models.CASCADE, null=True, blank=True) #views.py class SampleHomeView(ListView): model = Sample samples = Sample.objects.all context_object_name = 'samples' template_name = '<app name>/sample.html' ordering = ['-sample_date'] paginate_by = 10 #sample.html {% … -
Hosting django channels on apache and daphne
I am trying to deploy django chat application on apache the same way. Can someone please help me with setting up the daphne server? I am totally new to deploying django channels. I have a linux virtual machine (ubuntu). The site is running but the websocket connection is not established. the error I see in the console is: (index):16 WebSocket connection to 'ws://chat.bagdigital.in/ws/chat/lobby/' failed: (anonymous) @ (index):16 (index):30 Chat socket closed unexpectedly chatSocket.onclose @ (index):30 here is my apache conf file. <VirtualHost *:80> ServerName chat.bagdigital.in #ServerAdmin webmaster@localhost #DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error_chat_bagwebsite.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/pksingh/chat-app/chat-api/static Alias /media /home/pksingh/chat-app/chat-api/media <Directory /home/pksingh/chat-app/chat-api/static> Require all granted </Directory> <Directory /home/pksingh/chat-app/chat-api/media> Require all granted </Directory> <Directory /home/pksingh/chat-app/chat-api/chatapi> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/pksingh/chat-app/chat-api/chatapi/wsgi.py WSGIDaemonProcess bag_chat_app python-path=/home/pksingh/chat-app/chat-api python-home=/home/pksingh/chat-app/chat-api/venv WSGIProcessGroup bag_chat_app I have installed the redis server. And the socket connection is running fine if I run the django server at port 8000 normally without using apache. python3 manage.py runserver 0.0.0.0:8000 & Can someone help me with setting up daphne server here?? -
Django: How to manually render each field of a form on a bootstrap template?
I've found this nice bootstrap template online and I want to use it as my template for updating a user profile, I have tried several methods I've found in here and also in youtube, but I still couldn't get it to work. Not only does the form isn't rendering, the updated profile is not being saved also when I click update. Could someone help me out what is the problem? and I do apologize in advance if I'm not making sense as english is my second langauge. here is my view for profile update, I did not create a form for it as I've read online that I do not need to create a form for it to work, just need the model. class TutorProfileUpdateView(UpdateView): model = User fields = ['first_name', 'last_name', 'email', 'phone number', 'current_address', 'image', 'bio'] template_name = 'account/tutor_dashboard.html' success_url = reverse_lazy('tutor-dashboard') def form_valid(self, form): fm = form.save(commit=False) fm.user = self.request.user fm.save() messages.success(self.request, f'Profile Updated!') return HttpResponseRedirect(self.get_success_url()) and here is some part of the template, I will not paste it all here as it is too long. <form method="POST"> {% csrf_token%} <div class="card h-100"> <div class="card-body"> <div class="row gutters"> <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12"> <h6 class="mb-2 text-primary">Personal … -
Django - Best practice for running (switching) dev/debug/product mode?
In my source (using Docker), there is a database and my django code. docker-compose.yml services: app: db: When I debug locally, I usually delete the database in Docker-compose to prevent it creating a new database locally. Then I change the settings in django source to connect to the database of the server settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': 123.231.***, 'NAME': db***, 'USER': ****, 'PASSWORD': **** } } or When I develop a new feature, I would prefer to create a database locally to test things our rather than connect directly to the server database. Well, my question is that how to set things up so we can easily switch between dev/ prod/ debug mode. In my thought, it should be easy like commanding: python manage.py run dev-mode -
Serving media files in Django , gunicorn and nginx
I have deployed my Full Stack application using Django and React using nginx on AWS . All the files including static files are being served as expected but I am unable to serve media files present in the /home/user/backend/media/images/ directory . My directory structure looks as follows /home/user/backend/media/images/image1.jpg, /home/user/backend/media/images/image2.jpg etc. In development (manage.py runserver) mode I am able to access my files using http://localhost:8000/media/images/image1.jpg . here is my Nginx configuration file : server { listen 80; server_name xxxxxxxxx; root /home/user/frontend/build; index index.html; location / { root /home/user/frontend/build; try_files $uri /index.html; } location = /favicon.ico { access_log off; log_not_found off; } location /django_static/ { root /home/user/backend; } location /media/images/ { include /etc/nginx/mime.types; root /home/user/backend; } location /api/{ proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/user/backend/backend.sock; } } Here is my media settings in settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Here is my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api/',include('api.urls'))] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Also when i try to access the files using http://server/media/images/image1.jpg the browser just times out and i get no response , so I nothing is logged in /var/log/nginx/error.log . This is my first deployment so any help is … -
DRF: how to mix model fields directly inside a serializer
Suppose I have class Model1(models.Model) first_name = models.CharField(_('first name'), max_length=150, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) class Model2(models.Model): location = models.TextField() phone = models.CharField(max_length=15) I want to create a serializer using these fields. This has nothing to do with the models or the POST transaction. Just i want to use the definition of the models class CombinedSerializer(serializer.ModelSerializer): class Meta: model = Model1 fields = ['first_name'] model = Model2 fields = ['location'] So that i dont have to define them again. -
Dango rest framework: mixing some fields of one model with another and make a serializer
I have the User model and UserProfile model. User model contains the following: email password first_name last_name and UserProfile model contains class UserProfile(models.Model): user = models.OneToOneField(on_delete=models.CASCADE, primary_key=True) photo = models.ImageField() location = models.TextField() phone = models.CharField(max_length=15) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I want to create an api endpoint where User can edit the following fields and save after login --> from User first_name last_name --> from Userprofile photo location phone In normal Django forms. I can use multiple forms and validate them and save. User will see them as one form. In serializers how can I do this -
Fixing a type error for xhtm2pdf in a Django Project
I am trying to generate a PDF for my Django Project. I have used pip install xhtml2pdf The PDF was generate with plain text but when I added style in the pdf.html I got this Exception Type: TypeError: '<' not supported between instances of 'int' and 'NoneType' Here is the views.py: def admin_order_pdf(request,info_id): info = get_object_or_404(Info, id=info_id) template_path = 'businessplan/pdf.html' context = {'info': info} # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') # response['Content-Disposition'] = 'attachment; filename="report.pdf"' response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Info.id) # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF(html, dest=response) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response Here is the pdf.html {% load static %} <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static 'css/report.css' %}" /> <!-- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">--> <title>{{ info.businessName }}</title> <style> @charset "UTF-8"; @font-face { font-family: Fira Sans; font-weight: 400; src: url('/static/img/FiraSans-Regular.otf'); } @font-face { font-family: Fira Sans; font-style: italic; font-weight: 400; src: url('/static/img/FiraSans-Italic.otf'); } @font-face { font-family: Fira Sans; font-weight: 300; src: url('/static/img/FiraSans-Light.otf'); } @font-face { font-family: Fira Sans; font-style: italic; font-weight: … -
Django static files not showing
I hav gone through my settings.py file to look at my static file setting STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_ROOT = os.path.join(BASE_DIR,'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') but all my static files are nt showing when the page loads. Please what could be going on