Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Create Multiple Modal Dynamically in a Single Page
I am doing a Django Blog Project and it fetch all Blogs from the Database and show Blog Title in User Profile only. I want to create Bootstrap Modal for each Blog that is shown in the profile. Whenever a User click on a Title, the Modal will appear with Details. {% for blog in blogs.all %} <div class="card mb-4 shadow-sm "> <p class="card-text "><h2>{{ blog.title }}</h2></p> <div class="card-body"> <div class="btn-group"> <!-- Open a Modal for the blog --> <!-- Button To Implement the Modal--> <button id = "modalToggle" type="button" class="btn btn-sm btn-outline-secondary" data-toggle="modal" data-target="#modal">View More</button> <!-- Modal --> <div class="modal fade" id="modal" role="dialog"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">{{ blog.title }}</h4> </div> <div class="modal-body"> <p>{{ blog.body }}</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> </div> </div> Here all Blogs are showing the Modal of the first one. I cannot create multiple modals for each Blog. -
Django ModelChoiceField auto select views passed value
I have a simple problem with ModelChoiceField , I have a Classification class with four fields (name, price1, price2, price3) , I added an edit button and its working perfectly , i added the name on edit page as a ModelChoiceField , My problem is that am trying to force select the name value when edited so the user will only be able to change prices values . I read the doc about ModelForm which led me to this https://docs.djangoproject.com/en/2.2/ref/forms/api/#django.forms.Form.initial I tried initial= but it did not worked as i though it would. Any idea of either dynamically select the value or just print the name without allowing the user to change it would be great . here is my code , views.py def edit_class(request, name): classifications = Classification.objects.all() devices = Devices.objects.all() inst = Classification.objects.get(name=name) if request.method == 'POST': classification = EditClassForm(request.POST, instance=inst) if classification.is_valid(): classification.save() return redirect("/classifications.html") else: classification = EditClassForm() return render(request, 'classifications.html', {"form": classification, "classifications": classifications, "devices": devices}) forms.py class EditClassForm(forms.ModelForm): class Meta(object): model = Classification fields = ("name", "price1", "price2", "price3") def __init__(self, *args, **kwargs): super(EditClassForm, self).__init__(*args, **kwargs) self.fields['name'] = forms.ModelChoiceField(queryset=Classification.objects.all(), initial=0) self.fields['name'].widget.attrs.update({'class': "form-control"}) self.fields['price1'].widget.attrs.update({'class': "form-control", 'value': 0}) self.fields['price2'].widget.attrs.update({'class': "form-control", 'value': 0}) self.fields['price3'].widget.attrs.update({'class': "form-control", 'value': 0}) … -
Django Query Models Based Time and ForeignKey Value
I need help with querying Django objects. I have 3 models: Building, Map, and Report. A single building can have many maps. A single map can have many reports. Given the name of a building I would like to find the most recent report for each floor. That is, I want a list of Reports where each report has a different floor and each report is the most recent report for that floor. class Building(models.Model): building_id = models.AutoField('BID', auto_created=True, primary_key=True) name = models.CharField('Name', max_length=128) class Map(models.Model): map_id = models.AutoField('MID', auto_created=True, primary_key=True) building_id = models.ForeignKey(Building, on_delete=models.CASCADE, default=1) floor = models.CharField('Floor Number', max_length=128) class Report(models.Model): report_id = models.AutoField('RID', auto_created=True, primary_key=True) map_id = models.ForeignKey(Map, on_delete=models.CASCADE, default=1) building_id = models.ForeignKey(Building, on_delete=models.CASCADE, default=1) created_date = models.DateTimeField(auto_now_add=True) I have some pseudo-code below, but there must be an easier way using Django filters. Any ideas? name = "Mall" # All of the buildings reports reports = Reports.filter(building_id__name= name) floors_seen = [] latest_reports = [] for report in reports: floorNumber = report.map_id.floor_num if floorNumber not in floors_seen: floors_seen.append(floorNumber) latest_reports.append(report) else: for latest_report in latest_reports: if latest_report.map_id.floor_num == floorNumber: if report.created_date > latest_report.created_date: latest_reports.remove(latest_report) latest_reports.append(report) -
Direct assignment to the forward side of a many-to-many
I am trying to assign value to a ManyToManyField, however, any attempt I make to set a value on the db fails. Below is my simplified models.py class AppointmentRequest(models.Model): my_name = models.TextField(default='') requester_name = models.TextField(default='') meeting_date = models.TextField(default='') class CustomUser(AbstractUser): firstname = models.TextField(default='') appointments = models.ManyToManyField(AppointmentRequest) Below is the function in views.py that handles some functionality: from .models import AppointmentRequest def book_appointment(request, template_name) apt_request = AppointmentRequest() apt_request.requester_name = requesting_user apt_request.meeting_date = date apt_request.save() update_user.appointments = apt_request update_user.save() With the above I get the following error Direct assignment to the forward side of a many-to-many set is prohibited. Use appointments.set() instead. However, if I use set instead of =, I get the following error django manytomany 'str' object has no attribute 'set'. I am not sure what the problem is. Please help. -
Is it possible to create multiple model instances from a list of lists derived from another model?
I have two models, RecurringEvent and Event. The RecurringEvent models basic purpose is to create a list of datetimes, that is then to be used to create multiple events in the Event model. I have tried the save method with a for loop. However, no new Events are created, nor are any errors given. I’m not sure if its related to my loop (probably is). I’ve tried it a few different ways (using a list of named tuples, plain list of lists, rewriting the for loop in different ways) and have been unsuccessful. Is a model.manager needed to do this? I appreciate any help and would definitely like to know of any better ways to go about this. models.py class ReccuringEvent(models.Model): semester_start = models.DateField(null=True, blank=True) semester_end = models.DateField(null=True, blank=True) lesson_start = models.TimeField(null=True, blank=True) lesson_end = models.TimeField(null=True, blank=True) title = models.CharField(max_length=255, null=True, blank=True) … recurring_event_list = […] recurring_event_list_namedtuple = namedtuple('event', ['title', 'start', 'end']) recurring_event_list_named = [recurring_event_list_namedtuple(*d) for d in recurring_event_list] def save(self, *args, **kwargs): for d in range(len(recurring_event_list_named)): Event.objects.create(recurring_event_list_named) super().save(*args, **kwargs) # have tried including super(Event, self)… class Event(models.Model): title = models.CharField(max_length=200, null=True) description = models.TextField(max_length=255, null=True, blank=True) start = models.DateTimeField(null=True, blank=True) end = models.DateTimeField(null=True, blank=True) -
Python save/reload cache upon de-deployment
I have the following function in my django project which calls an external api with caching setup hourly as follows: @cached(cache=TTLCache(maxsize=1000, ttl=settings.CACHE_EXPIRATION_HOURLY)) def get_external_data(zip_code): my_url = MY_API.format(zip_code) my_response = requests.request( 'GET', url=my_url, headers={ 'zip-code': zip_code } ) return my_response As far as i know, local caches will likely be cleared when the web servers are re-deployed or when the runserver restarts. How do you prime or save/reload the cache to avoid a spike in backend traffic each deployment? -
Django: Clone instance, Multiple Model Forms
I would like to clone an instance of my object. I am aware of the solution to: obj = ProductModel.objects.get(pk=self.object.id) obj.pk = None as described in many references, such as Link However, I struggle to implement this solution when I need to refer to a super. How can I modify the object already at start so super refers to the modified obj.pk = None ? My View.py looks like below but the super refers to the original object and not the modified object: class ProductUpdateView(UpdateView): model = Product slug_field = 'product_uid' obj = Product.objects.get(pk=self.object.id) obj.pk = None def get_context_data(self, **kwargs): context = super(ProductUpdateView, self).get_context_data(**kwargs) context['form_1'] = ModelForm_1(instance=self.obj) context['form_2'] = ModelForm_2(instance=self.obj) return context def form_valid(self, form): self.object = form.save() return super().form_valid(form) def get_success_url(self): return reverse('product-list') -
ModuleNotFoundError: No module named 'payment_info'
I am trying to run my experiment again but I get an error message when I try to execute it. However, I don't know why since I didn't change anything. This is what the Traceback says Traceback (most recent call last): File "c:\users\wiwi-admin\appdata\local\programs\python\python37\lib\site-packages\otree_startup\__init__.py", line 214, in do_django_setup django.setup() File "c:\users\wiwi-admin\appdata\local\programs\python\python37\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "c:\users\wiwi-admin\appdata\local\programs\python\python37\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "c:\users\wiwi-admin\appdata\local\programs\python\python37\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "c:\users\wiwi-admin\appdata\local\programs\python\python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'payment_info' PS C:\Users\Wiwi-Admin\Desktop\Master thesis code\__pycache__\oTree> -
How can I access django admin when my app is live it give me server error 500?
I have an app made on django 2.2.5. I was trying to access the django admin so that I can add some data for the app using admin. When I was accessing the admin on the development server by calling 127.0.0.1:8000/admin everything is going fine and I can add more data to the database using admin page. But I am unable to access my admin page when I am fetching the admin by using(my deployed website ip say(10.2.2.5)/admin. My admin page is opening but as soon as I am trying to login into it using my id and password it is giving me error(server error 500). Can someone help me so that I can add data to my website from the admin. Thanks in advance. -
Django Admin - Disable field by choice
I had a model like this class Content(models.Model): name = Model.CharField(max_length=255, blank=False, null=False) type = Model.CharField(max_length=1, blank=False, null=False, choices=CONTENT_CHOICE) lesson = Model.CharField(max_length=255, blank=False, null=False) exam = Model.CharField(max_length=255, blank=False, null=False) and CONTENT_CHOICE likes CONTENT_CHOICE = (("1", "Lesson"), ("2", "Exam")) My goal is, when the inputer insert a new record for this model from Admin, if the inputer select "Lesson", the field exam would be disable and vice versa. May you please advise me how to do it? I search some tutorial but all seem do not have any clue. Thanks. -
Django REST api and django_filter problem
I have problem with rest_framework.viewsets.ReadOnlyModelViewSet. class ProductFilter(filters.FilterSet): meat_type = filters.CharFilter(lookup_expr='slug__iexact') category = filters.CharFilter(lookup_expr='slug__iexact') class Meta: model = Product fields = { 'price': ['gte', 'lte'], } ordering_fields = ['price', ] class ProductViewSet(viewsets.ReadOnlyModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer filterset_class = ProductFilter @action(methods=['get'], detail=False) def get_products(self, request): products = self.get_queryset().order_by('-created') serializer = self.get_serializer_class()(products, many=True) print('SHOW IT') if len(products) == 0: return Response(status=status.HTTP_204_NO_CONTENT) return Response(serializer.data, status=status.HTTP_200_OK) My problem is that print in get_products not work, but code give good result with filters objects. My urls: router = routers.DefaultRouter() router.register('', views.ProductViewSet) urlpatterns = [ path('shop/', include(router.urls)) ] Tests: class TestViews(TestCase): def setUp(self): self.client = Client() self.url = "/api/shop/" self.search_url = "/api/shop/?price__lte={}&price__gte={}&meat_type={}&category={}" self.category1 = Category.objects.create(name='cattest1', slug='cattest1') self.category2 = Category.objects.create(name='cattest2', slug='cattest2') self.meat_type1 = MeatType.objects.create(name='meattest1', slug='meattest1') self.meat_type2 = MeatType.objects.create(name='meattest2', slug='meattest2') self.product1 = Product.objects.create(category=self.category1, meat_type=self.meat_type2, name='prodtest1', slug='prodtest1', price=50) self.product2 = Product.objects.create(category=self.category1, meat_type=self.meat_type1, name='prodtest2', slug='prodtest2', price=75) self.product3 = Product.objects.create(category=self.category2, meat_type=self.meat_type2, name='prodtest3', slug='prodtest3', price=20) self.product4 = Product.objects.create(category=self.category2, meat_type=self.meat_type1, name='prodtest4', slug='prodtest4', price=150) def test_get_products_all(self): response = self.client.get(self.url) self.assertEqual(200, response.status_code) self.assertEqual(4, len(response.data)) def test_get_products_no_content(self): Product.objects.all().delete() response = self.client.get(self.url) self.assertEqual(204, response.status_code) def test_product_greater_than(self): response = self.client.get(self.search_url.format( "", "55", "", "" )) self.assertEqual(200, response.status_code) self.assertEqual(2, len(response.data)) Test test_get_products_no_content fail with error: assertionError: 204 != 200. Somebody have any idea? Thanks for any answer Magnus -
Trying to send custom password reset email in latest Django version
I have the same question as this stack overflow: Does Django password_reset support html email templates? But, I could not get the solutions to work in the current Django version. The basic attempt render the html as a string. How do I get the html to render as html? my urls.py: path('accounts/password-reset/', auth_views.PasswordResetView.as_view( template_name='password_reset.html', html_email_template_name='password_reset_email_template.html', subject_template_name='password_reset_subject.txt' ), name='password_reset'), password_reset_email_template.html: <html> <tr> <td style="color:#333333; font-family: Helvetica, sans-serif;text-align:left; font-size:14px; line-height:20px; padding-bottom:18px;text-align:left;"> {% load i18n %} {% autoescape off %} You're receiving this e-mail because you requested a password reset for account. {% endautoescape %} <p>Follow the link below to reset:</p> <a href="https://domain{% url 'password_reset_confirm' uidb64=uid token=token %}"> Reset Password </a> </td> </html> I also tried to create a new view, but that does not render anything at all. def reset(request): return password_reset(request, template_name='password_reset.html', html_email_template_name='password_reset_email_template.html', subject_template_name='password_reset_subject.txt', post_reset_redirect=reverse('login')) -
Docker-compose cannot find file manage.py in runserver command
I what to dockerize my django app, i create my Dockerfile : FROM python:3.6-alpine RUN apk add --no-cache linux-headers libffi-dev jpeg-dev zlib-dev RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev RUN mkdir /DEV WORKDIR /DEV COPY ./requirements.txt . RUN pip install --upgrade pip RUN pip install -r requirements.txt ENV PYTHONUNBUFFERED 1 COPY . . at this point i create my docker-compose.yml: version: '3' networks: mynetwork: driver: bridge services: db: image: postgres restart: always ports: - "5432:5432" networks: - mynetwork environment: POSTGRES_USER: myuser POSTGRES_PASSWORD: mypass POSTGRES_DB: mydb volumes: - ./data:/var/lib/postgresql/data web: build: . command: python manage.py runserver 0.0.0.0:8000 networks: - mynetwork volumes: - .:/DEV ports: - "8000:8000" depends_on: - db then i create a .dockerignore file: # Ignore .DS_Store .idea .venv2 __pycache__ !manage.py *.py[cod] *$py.class *.so .Python *.log docker-compose.yml Dockerfile geckodriver.log golog.py golog.pyc log.html media out output.xml report.html startup.sh templates testlibs .dockerignore well, at this point i run: docker-compose build --no-cache at the end image was build correctly, but when i run: docker-compose up system return this error: web_1 | python: can't open file 'manage.py': [Errno 2] No such file or directory core_web_1 exited with code 2 Someone can help me about the issue? so many thanks in advance -
How to update selected fields in a model if the entry exists?
I am trying to update two fields in my models if the entry exists. If Campaign History exists, I want to update the call_cost and call_duration fields. I tried using check = CampaignHistory.objects.get(pk=campaign_id) But this raises an error since the CampaignHistory does not exist yet. # models.py class CampaignHistory(models.Model): """ Model to store Campaign History """ campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE) call_duration = models.IntegerField() call_cost = models.DecimalField(max_digits=10, decimal_places=6) # views.py def events(request, campaign_id): campaign = Campaign.objects.get(pk=campaign_id) account_sid = 'XXX' auth_token = 'XXX' client = Client(account_sid, auth_token) sid = request.GET.get('CallSid', default=None) detail = client.calls(sid).fetch() print("SID:{}\nCampaign:{}\nDuration:{}\nPrice:{}" .format(sid, campaign, str(str(detail.duration)+'s'), str(detail.price)[1:])) check = CampaignHistory.objects.get(pk=campaign_id) # this raises the error if check does not exists how do I fix this? if check: old_cost = check.call_cost new_cost = old_cost + float(detail.price) old_duration = check.call_duration new_duration = old_duration + int(detail.duration) check.call_cost = new_cost check.call_duration = new_duration check.save() else: campaign_history = CampaignHistory(campaign=campaign, call_duration=str(str(detail.duration) + 's'), call_cost=str(detail.price)[1:]) campaign_history.save() return render(request, "CallCenter/events.html") -
Python or PHP for a long term social media site? [on hold]
So I'm planning to build a social media network I'm familiar with PHP but I just thought about python is it more suitable than PHP for a long term project? or should I stick with PHP???? -
How to place Bokeh widgets precisely on an html page
I am struggling to place Bokeh widgets precisely where I want them on an html page built with Django. For example my views.py look like this: from bokeh.io import show from bokeh.layouts import column, row from bokeh.models import CustomJS, TextInput from bokeh.plotting import figure fig = figure(title='title') fig.line(x=[1,2,3], y=[1,2,3]) text_input = TextInput(title="Add graph title", value='') text_input.js_on_change('value', CustomJS( args={'title': fig.title, 'text_input': text_input}, code="title.text = text_input.value" )) widgets_layout = column(text_input) figures_layout = row(fig) #show(row(widgets_layout, fig)) # Set up page layout page_layout = row(widgets_layout, figures_layout) script, div = components(page_layout) return render_to_response('app/test.html', {'script':script, 'div':div}) and my html page (test.html) look like this: <!--Test page--> {% extends "base.html" %} {% load static %} {% load bootstrap4 %} {% load i18n %} {% block content %} <!--Bokeh--> <link href="http://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.css" rel="stylesheet" type="text/css"> <link href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.3.4.min.css" rel="stylesheet" type="text/css"> <link href="http://cdn.pydata.org/bokeh/release/bokeh-tables-1.3.4.min.css" rel="stylesheet" type="text/css"> <script src="http://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.3.4.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-tables-1.3.4.min.js"></script> <!--Figure--> <div class='col-lg'> <div class='card-lg bg-light' id='maincontent'> <h2> {% trans "Test" %}</h2> <hr> <div> {{ div | safe }} {{ script | safe }} </div> </div> </div> <br> {% endblock content %} Now, how can I move the little widget (text_input) to a precise position ? Any position will do, I just want to be able to place it pretty much … -
django: how to substract hours from datetime if both values are in fields?
qs = Model.objects.annotate(foo=F('datetime') - F('hours') * 3600) ^ throws an error about fields mismatch. How to tell django to tell DB that hours is an interval (time delta)? -
Docker-Compose can't connect to MySQL
I'm trying to connect Django project with MySQL using docker. I have the problem when upping docker-compose. It says the next error: I'm using port 3307, should i create first new database schema in my local? Or how can I do it because my default port is 3306 but if i try to use it, it says that is busy. My code here: Dockerfile FROM python:3.7 ENV PYTHONUNBUFFERED 1 ENV LANG=C.UTF-8 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN apt-get update RUN pip install -r requirements.txt ADD . /code/ Docker-compose version: '2' services: app: container_name: container_app build: context: . dockerfile: Dockerfile restart: always command: bash -c "python3 manage.py migrate && python manage.py shell < backend/scripts/setup.py && python3 manage.py runserver 0.0.0.0:8000" links: - db depends_on: - db ports: - "8000:8000" db: container_name: container_database image: mariadb restart: always environment: MYSQL_ROOT_HOST: 'host.docker.internal' MYSQL_DATABASE: 'container_develop' MYSQL_USER: 'root' MYSQL_PASSWORD: 'password' MYSQL_ROOT_PASSWORD: 'password' ports: - "3307:3307" settings.py: DATABASES = { 'default' : { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database_develop', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'db', 'PORT': 3307, 'CHARSET': 'utf8', 'COLLATION': 'utf8_bin', 'OPTIONS': { 'use_unicode' : True, 'init_command': 'SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED', }, } } -
Django Throttling Not Working on Production mode
I'm using DJANGO REST FRAMEWORK to protect my API. Django Throttling that limits the number of requests on an API for Anonymous and authenticates Users. The throttling is not working on production mode. By the way, I'm using Ubuntu and Nginx server for deploying my site. I use two way but both didn't work for me. Here are the codes. Please help me. I'm noob in django. 1st Method, Which I use is described below. Views.py class SustainedAnon(AnonRateThrottle): rate = '100/day' class BurstAnon(AnonRateThrottle): rate = '10/minute' class SustainedUser(UserRateThrottle): rate = '100/day' class BurstUser(UserRateThrottle): rate = '10/min' class ProductApi(generics.RetrieveAPIView, mixins.CreateModelMixin): lookup_field= 'puid' serializer_class = ProductApisSerializers """ Provides a get method handler. """ # permission_classes = (IsAuthenticated,) throttle_classes = (SustainedAnon,SustainedUser,BurstAnon,BurstUser) def get_queryset(self): return ProductApis.objects.all() def post(self, request,*args,**kwargs): return self.create(request, *args, **kwargs) URLS.PY from django.contrib import admin from django.urls import path, include from . import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ path('',views.index, name='index'), path('api/<slug:puid>/',views.ProductApi.as_view()), ] 2nd Method- DRF Views.py class ProductApi(generics.RetrieveAPIView, mixins.CreateModelMixin): lookup_field= 'puid' serializer_class = ProductApisSerializers """ Provides a get method handler. """ # permission_classes = (IsAuthenticated,) throttle_classes = [UserRateThrottle,AnonRateThrottle] def get_queryset(self): return ProductApis.objects.all() def post(self, request,*args,**kwargs): return self.create(request, *args, **kwargs) settings.py REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ], … -
How to convert form field data before saving to database in a Django ModelForm?
I'm creating an "edit" page in Django python framework (template 'edit_page.html') where user should be able to edit existing data stored in a database. For now I can easily retrieve existing raw data in user form (a Django template), my issue is that I need to convert data populated by user before saving the form. I have an 'ipv4' field in my model mapping a database table column with IPv4 addresses stored as unsigned int. For instance ip address '10.0.0.0' is stored as 167772160 in the database. Data conversion for 'ipv4' could be implemented as follows (exemple): # Convert from raw database to human friendly format (167772160 -> 10.0.0.0) import ipaddress ipv4_raw = 167772160 ipv4_friendly = str(ipaddress.ip_address(ipv4_raw)) print(ipv4_friendly) # Output: 10.0.0.0 # Convert from human friendly format to raw database format (10.0.0.0 -> 167772160 ) import ipaddress ipv4_friendly = '10.0.0.0' ipv4_raw = int(ipaddress.ip_address(ipv4_friendly)) print(ipv4_raw) # Output: 167772160 My form needs to show human friendly 'ipv4' to the user but must have the capability to update the database column in 'raw' format (int). 'ipv4' must be converted from raw format to user friendly format for display and the other way around for database update. Where should I perform this operation and … -
How to edit model objects in an inline formset in Django
In Django I am trying to use an inline formset factory so a user can edit instances of a model related to a parent model via a foreignkey. For some reason the methods I am trying don't save the changes I make when I click submit. My view is like this (not including render): def edit_sets(request, exercisegroup_id): exercisename = ExerciseName.objects.get(pk=exercisegroup_id) SetLoggerFormSet = inlineformset_factory(ExerciseName, SetLogger, fields=('weight','reps',)) formset = SetLoggerFormSet(instance=exercisename) if request.method == 'POST': formset = SetLoggerFormSet(request.POST, instance=exercisename) if formset.is_valid(): formset.save() else: formset = SetLoggerFormSet(instance=exercisename) and I am displaying each form in the formset in my template so the user can individually edit the instance: <form method="post">{% csrf_token %} {{ formset.management_form}} <table> {% for form in formset %} {{ form }} {% endfor %} </table> <button type="submit" class="save btn btn-default">Save set</button> </form> Stuck as to why this isn't working. The form displays as it should and this method has previously worked for adding objects, but I am still unable to use it to replace one of those objects in the queryset. Am I missing something I should be doing differently? -
Cant update custom model using custom form in Django
I've two models and I want to update them at the same time with one submit button. First model is User which is from contrib models and default. Second model is UserProfile which has OneToOneField with user. Im making instance of both and rendering both forms at same time. When I update, one one instance (User) is updating, my custom model userprofile is not updating. Sorry im new and have been figuring out what is wrong in my code. Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import UserProfile from django.contrib.auth.forms import UserChangeForm class EditProfileForm(UserChangeForm): class Meta: model = User fields = ('email', 'first_name', 'last_name', 'password') class EditProfileForm2(forms.ModelForm): city = forms.CharField() description = forms.CharField() phone = forms.IntegerField() class Meta: model = UserProfile fields = ('city','description','phone') def save(self, commit=True): user = super(EditProfileForm2, self).save(commit=False) user.city = self.cleaned_data['city'] user.description = self.cleaned_data['description'] user.phone = self.cleaned_data['phone'] if commit: user.save() return user Views.py from django.shortcuts import render, redirect from .forms import RegistrationForm, EditProfileForm, EditProfileForm2 from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, logout, authenticate from django.contrib import messages from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm from django.contrib.auth import update_session_auth_hash def edit_profile(request): if request.method == 'POST': form = … -
Problem with Django: No module named 'myapp'
Good afternoon, I'm new to Django and I'm trying to follow a tutorial. However, when running the server, the following error pops up: File "C:\Users\Jorge\PycharmProjects\web\mysite\mysite\urls.py", line 18, in <module> from myapp.views import * ModuleNotFoundError: No module named 'myapp' This is a screenshot about how my files are right now: enter image description here -
Looking for a Admin Theme For an ERP Project
I am going to start a new Project in Laravel it would be a whole solution for a School ERP & many integrated systems. So can some suggest me a decent good looking / simple bootstrapped based premium admin theme. Thanks in adva -
Django ignore_conflicts doesn't work for User model
I am trying to create a lot of users for testing my Django application. I've used this method on other models and it works, but here it doesn't. When executed it states the error below. The latest Django version (2.2.6) was used. The documentation states: (...) setting the ignore_conflicts parameter to True tells the database to ignore failure to insert any rows that fail constraints such as duplicate unique values. My Code: def draftUser(i): return User(username='Testguy' + str(i), first_name=randomString(7), last_name=randomString(5)) user_cache = [] for i in range(1, 10000): user_cache(draftUser(i)) User.objects.bulk_create(user_cache, ignore_conflicts=True) The last line of the error code: django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username