Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django keeps throwing a UNIQUE constraint failed error every time I try to save a new foreign key instance
I have a foreignkey connected to a django model. I would like there to be numerous instances to the django model through foreign keys. My first foreign key saved to the model is saved successfully but every other foreignkey that is saved after that incident keeps throwing back this error: UNIQUE constraint failed: moderator_product.product_id. I can't seem to figure out where I'm going wrong. class Detail(models.Model): name = models.CharField(max_length=30, blank=True) location = models.CharField(max_length=300, blank=True) lat = models. DecimalField(max_digits=9, decimal_places=6) lng = models.DecimalField(max_digits=9, decimal_places=6) slug = models.SlugField(max_length=100, unique=True, default='') open = models.IntegerField() close = models.IntegerField() def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Detail, self).save(*args,**kwargs) class Store_image(models.Model): image = models.OneToOneField(Detail, on_delete=models.CASCADE, primary_key=True,) image = models.FileField(blank=True) class Product(models.Model): product = models.ForeignKey(Detail, on_delete=models.CASCADE,unique = False,) name = models.CharField(max_length=100, blank = True) price = models.IntegerField() description = models.CharField(max_length = 500, blank= True,) product_image = models.FileField(blank=True) def addproduct(request,slug,pk): Detail = Detail.objects.get(pk=pk) if request.method == "POST": name = request.POST.get("name") price = request.POST.get("price") description = request.POST.get("description") image = request.FILES['image'] Detail.product_set.create(name=name,price=price, description=description, product_image=image,) return render(request,"moderator/addproduct.html") -
How can i add spans after input tags in django without rendering forms manually?
I want to add span tags after input tags in forms to show icons or so. the idea is in Django the forms is just rendered automatically by calling the form's context name in a template tag so is there any way I can add tags to each or only one tag without rendering the whole form manually? can I add anything in the forms.py file to make these changes? -
Problem: Any logged-in user can access Django Admin panel
I have my account with is_superuser = 1 and other users with is_superuser = 0 and is_staff = 0. But Django does not restrict access to "not-staff" users. So, any logged-in user can access admin panel. From Django documentation: By default, logging in to the admin requires that the user has the is_superuser or is_staff attribute set to True. But this does not work. I do not have any changes in admin settings. Except custom admin panel URL: from django.contrib import admin urlpatterns = [ path('my-admin/', admin.site.urls), ] So where can be the problem with not working Django restrictions? Django==2.2.4 Database: MySQL -
Why JSON.stringify() return undefined and produce auth.js:65 Uncaught (in promise) TypeError: Cannot read property 'data' of undefined?
I'm trying to login in my django application using axois and react-redux. My problem is when I entered wrong login information then the LOGIN_FAIL action is work fine but when entered correct login information the LOGIN_SUCCESS action is not work and produce the following error "Uncaught (in promise) TypeError: Cannot read property 'data' of undefined". I have debugged my code and this line "const body = JSON.stringify({ username, password });" is return undefined even username and password data is successfully received. Is the problem heppend this reason? I am confused!! Can anyone solve my problem? Thanks in advance. Here is my action code: import axios from "axios"; import { errorMessage } from "./messages"; import { USER_LOADING, USER_LOADED, AUTH_ERROR, LOGIN_SUCCESS, LOGIN_FAIL } from "./types"; // Login User export const login = (username, password) => dispatch => { // Headers const config = { headers: { "content-type": "application/json" } } // Request body const body = JSON.stringify({ username, password }); axios.post("/api/auth/login", body, config) .then(res => { dispatch({ action: LOGIN_SUCCESS, payload: res.data }); }).catch(err => { dispatch(errorMessage(err.response.data, err.response.status)); dispatch({ type: LOGIN_FAIL }); }); } -
Failed to start uWSGI Emperor
following the best tutorials on the internet, still not able to make emperor.uwsgi.service working. my configuration files as follows: /etc/uwsgi/emperor.ini emperor = /etc/uwsgi/vassals uid = user1 gid = www-data limit-as = 1024 logto = /var/log/uwsgi.log /etc/uwsgi/sites/project.ini [uwsgi] project = project base = /home/user1/project uid = user1 gid = www-data plugins = python3 chdir = %(base) home = %(base)/venv #module = project.wsgi:application wsgi-file = /home/user1/project/project/wsgi.py workers = 4 master = true processes = 10 socket = /home/user1/%(project)/%(project).sock chown-socket = %(uid):www-data chmod-socket = 664 vacuum = true buffer-size = 65535 /etc/uwsgi/vassals/(ln -s) /etc/systemd/system/emperor.uwsgi.service [Unit] Description=uWSGI Emperor After=syslog.target [Service] ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown user1:www-data /run/uwsgi' ExecStart=/usr/local/bin/uwsgi --ini /etc/uwsgi/emperor.ini # Requires systemd version 211 or newer RuntimeDirectory=uwsgi Restart=always KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all [Install] WantedBy=multi-user.target all files under the same uid, gid user1:www-data I tried a lot of things and I found some other directories for uwsgi, I changed the user in #/etc/init.d/uwsgi, and I found the emperor file in the same location, I don't know what else I should modify. the error messages I get when I run systemctl status emperor.uwsgi.service Process: 788 ExecStart=/usr/local/bin/uwsgi --ini /etc/uwsgi/emperor.ini (code=exited, status=1/FAILURE) Aug 04 18:03:26 mymachine systemd[1]: emperor.uwsgi.service: Service RestartSec=100ms expired, scheduling restart. Aug 04 18:03:26 … -
mysql query to django ORM
I am trying to make a query with django ORM but I could not. The models are: class Prestamo(models.Model): PENDIENTE = 1 PAGADO = 2 FUSIONADO = 3 ANULADO = 4 ESTADOS = ( (PENDIENTE, 'pendiente'), (PAGADO, 'pagado'), (FUSIONADO, 'fusionado'), (ANULADO, 'anulado') ) cliente = models.ForeignKey(Cliente, on_delete = models.CASCADE) fecha_prestamo = models.DateField(default=timezone.now) capital_prestado = models.FloatField() porcentaje_aplicado = models.ForeignKey(Interes, on_delete=models.CASCADE) valor_interes = models.FloatField(null=True) fecha_registro = models.DateTimeField(default=timezone.now) prestamo_nuevo = models.ForeignKey('Prestamo', on_delete=models.CASCADE, blank= True, null=True) estado = models.IntegerField(choices=ESTADOS, default=PENDIENTE, blank= True) class Abono(models.Model): prestamo = models.ForeignKey(Prestamo,on_delete=models.CASCADE) fecha_abono = models.DateField(default=timezone.now) valor_abono_capital = models.FloatField() valor_abono_interes = models.FloatField() class Descuento(models.Model): prestamo = models.ForeignKey(Prestamo,default=None,on_delete=models.CASCADE) fecha_descuento = models.DateField(default=timezone.now) valor_descuento = models.FloatField() I have the following query in MySQL which is the one I need but in django ORM, In this I am making a query to the three tables of loan, credit and discount. left join is required because a loan may not have payments yet made and no discounts select p.id,fecha_prestamo,p.capital_prestado,CONCAT(clientes_cliente.nombres,' ', clientes_cliente.apellidos) 'Cliente', IFNULL(sum(prestamos_abono.valor_abono_capital), 0) abonos, (select IFNULL(sum(prestamos_descuento.valor_descuento) , 0) from prestamos_descuento where prestamos_descuento.prestamo_id = p.id) 'descuentos', (p.capital_prestado - IFNULL(sum(prestamos_abono.valor_abono_capital), 0) - (select IFNULL(sum(prestamos_descuento.valor_descuento) , 0) from prestamos_descuento where prestamos_descuento.prestamo_id = p.id) ) 'saldo capital' from prestamos_prestamo as p left join prestamos_abono ON prestamos_abono.prestamo_id = p.id … -
How to add field in admin/app/add panel which wont be included in model in Django?
I have to add extra field in Django admin/app/add panel which wont be included in my model, but I want to use the value in Model.save() method. It must be like: on "add" panel I can enter minutes and seconds, but in model.save() I save only mins*60+seconds. -
DoesNotExist at /admin/login/ Site matching query does not exist in wagtail
I can't do anything in my admin panel because when i go to locahost:8000/admin it shows those errors: DoesNotExist at /admin/login/ Site matching query does not exist. Full traceback: Environment: Request Method: GET Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 2.2.3 Python Version: 3.7.3 Installed Applications: ['home', 'search', 'blog', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'django.contrib.sites', 'django_comments_xtd', 'django_comments'] Installed Middleware: ['django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.core.middleware.SiteMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware'] I also tried this question but it also throws errors: Traceback: File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/contrib/sites/models.py" in _get_site_by_request 39. SITE_CACHE[host] = self.get(domain__iexact=host) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/db/models/query.py" in get 408. self.model._meta.object_name During handling of the above exception (Site matching query does not exist.), another exception occurred: File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/wagtail/admin/urls/__init__.py" in wrapper 102. return view_func(request, *args, **kwargs) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return … -
How do I fix this fake scripting in django? It doesn't work for me
I'm using the Faker for fake populating my database, but it doesn't work. It says my models doesn't have "objects" member and the Faker itself doesn't work. I tried to run this file with python, I get errors. import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') import django django.setup() ## FAKE POP SCRIPT import random from first_app.models import Topic, Webpage, AccessRecord from faker import Faker fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): # Add topic for the entry top = add_topic # Create fake data for that entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # Create the new webpage entry webpg = Webpage.objects.get_or_create(topic=top,url=fake_url, name=fake_name)[0] # Create a fake access record for that webpage acc_rec = AccessRecord.objects.get_or_create(name=webpg, date=fake_date)[0] if __name__ == "__main__": print("Populating Script!") populate(20) print("Populating Complete!") I expect the output of the "Populating the databases...Please Wait" and the fake populating my database and then after it's finished, "Populating Complete" should be printed. -
Send 2 args to Celery eta task
I use eta to program a task: test.apply_async(eta=datetime(2019, 8, 4, 17, 01)) but I have a task on test.py that take an arg from view, for example 'post': app = Celery() @app.task(bind=True) def test(post, self): #somecode I need to pass 'eta' and 'post', I try with: test.apply_async(post, eta=datetime(2019, 8, 4, 17, 01)) but give an error: functools.partial object argument after * must be an iterable, not Author what's wrong? -
Ceate a ImageField from an existing URL
I'm creating ImageField on one machine (uploading an image to aws) and I want to create the same ImageField on another machine with this already existing url. How can I do that? -
deserializing a model with a custom field
I have a model in django with a 3rd party CustomField. dumpdata works fine serializing the field to json, but loaddata is unsuccessful in deserializing this specific field (due to a bug in the code of the CustomField). How can I write a deserializer to overwrite the original deserializer of the field in a way that django can use it in loaddata command. class MyModel(models.Model): id = models.IntergerField() custom = CustomField() -
Why isn't my code working properly with enviroment variable?
So if-else statement executes like it receives True instead of False, however the print statement displays "False" but god knows why 2 times. But when I just assign False to DOCKER in settings.py it works as expected. settings.py: import os from datetime import timedelta import environ env = environ.Env( # set casting, default value DEBUG=(bool, False) ) environ.Env.read_env() DEBUG = env('DEBUG') BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = env('SECRET_KEY') DOCKER = False # env('DOCKER') print(DOCKER) if DOCKER: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'answerly', 'USER': 'ubuntu', 'PASSWORD': 'ubuntuanswerly', 'HOST': 'db', 'PORT': '5432', } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'answerly', 'USER': 'ubuntu', 'PASSWORD': 'ubuntuanswerly', 'HOST': 'localhost', 'PORT': '5432', } } .env: DEBUG=on SECRET_KEY=')fv!ujycyce4rf##exy8q=zbo4)o5dano73-o9(g3ni-41)ed*' DOCKER=False -
complex django Query, I dont know how to do it
I have a problem that is bursting my head and I could not solve. I don't know how to make a query using the Django ORM to get the correct result. I am using MySQL, The situation is as follows: Models: class Prestamo(models.Model): PENDIENTE = 1 PAGADO = 2 FUSIONADO = 3 ANULADO = 4 ESTADOS = ( (PENDIENTE, 'pendiente'), (PAGADO, 'pagado'), (FUSIONADO, 'fusionado'), (ANULADO, 'anulado') ) cliente = models.ForeignKey(Cliente, on_delete = models.CASCADE) fecha_prestamo = models.DateField(default=timezone.now) capital_prestado = models.FloatField() meses_plazo = models.IntegerField() porcentaje_aplicado = models.ForeignKey(Interes, on_delete=models.CASCADE) valor_interes = models.FloatField(null=True) saldo_capital = models.FloatField(null=True) saldo_interes = models.FloatField(null=True) tipo_prestamo = models.ForeignKey(TiposPrestamo, on_delete=models.CASCADE) fecha_registro = models.DateTimeField(default=timezone.now) prestamo_nuevo = models.ForeignKey('Prestamo', on_delete=models.CASCADE, blank= True, null=True) #estado = models.ForeignKey(EstadoPrestamo, on_delete = models.CASCADE, blank= True, default=1) estado = models.IntegerField(choices=ESTADOS, default=PENDIENTE, blank= True) observaciones = models.TextField(max_length=150,blank=True) usuario = models.ForeignKey(User, on_delete= models.CASCADE, default='') def __str__(self): return "{0},{1},{2}".format(self.fecha_prestamo, self.cliente, self.capital_prestado) class Abono(models.Model): prestamo = models.ForeignKey(Prestamo,on_delete=models.CASCADE) fecha_abono = models.DateField(default=timezone.now) valor_abono_capital = models.FloatField() valor_abono_interes = models.FloatField() observaciones = models.TextField(max_length=100,blank=True,null=True) fecha_registro = models.DateTimeField(default=timezone.now) estado = models.ForeignKey(EstadoAbono, on_delete = models.CASCADE, blank= True, null=True) usuario = models.ForeignKey(User, on_delete= models.CASCADE, default='') def __str__(self): return "{0},{1}".format(self.fecha_abono, self.valor_abono_capital) class Descuento(models.Model): prestamo = models.ForeignKey(Prestamo,default=None,on_delete=models.CASCADE) fecha_descuento = models.DateField(default=timezone.now) valor_descuento = models.FloatField() fecha_registro = models.DateTimeField(default=timezone.now) descontadopor = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return … -
Best way to hold and then display employee information on a page?
I hope everyone's doing well. I am making a little Time Attendance Application where the employee Checks in and Checks out. I am making this a Web App based on the Django python framework. I want to understand the best way to hold the data of these employees but then also display it in a separate page for each employee. So far, I've made a table in my MySQL like: INSERT INTO employees (employee_id INT(50), first_name VARCHAR(25), last_name VARCHAR(30), age INT(80), mobile_no VARCHAR(16), email VARCHAR(100) Everytime I want to create a new employee, I have a page that opens and takes in the employee's details and inserts everything to the database. I also have a table on the homepage (that only the admin can see) that displays the employees and their details but if we click a tr, I want it to open a page containing that employee's details so I can change anything I want or even delete that employee. I understand that the page will have to fetch the details about that employee from the database and then anything I change and save the changes of, will be modified in the database. It's just like how you would … -
Model changes done in tasks not persisting
I am trying to call a task to be completed asynchrously because it takes a long time to complete and the request will timeout if I wait for it to be completed (I'm doing some processing on an image and getting the results). When I put prints into the task, I see it's getting executed, so I know it's not an issue with that. When I save the model, it acts like it saved but doesn't actually permanently save it. project > project > settings.py import environ env = environ.Env() CELERY_BROKER_URL = env.str('BROKER_URL', 'amqp://qisdvxct:b0iKxulu3z2evLScg1hnCNfWflDEBBm2@lion.rmq.cloudamqp.com/qisdvxct') CELERY_RESULT_BACKEND = 'django-db' INSTALLED_APPS = [ ... 'django_celery_results', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } MEDIA_URL = '%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME DEFAULT_FILE_STORAGE = 'accounting.s3utils.MediaRootS3BotoStorage' MEDIA_ROOT = MEDIA_URL STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') project > project > init.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) project > project > celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. … -
Django unique slug prepopulated_fields problem
I have a minor issue, while i create a game objects, slug field auto populated. For example if i write lorem ipsum, slug field autopopulate in this way "lorem-ipsum". However, when I try to create another object with the same name, I get this error. " this slug already exists " Expected output : lorem-ipsum-1 but it doesn't works admin.py prepopulated_fields = {'slug': ('name',)} models.py name=CharField(max_length=255) slug = models.SlugField(unique=True, max_length=255) def get_unique_slug(self): slug = slugify(self.name.replace('ı', 'i')) unique_slug = slug counter = 1 while Game.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, counter) counter += 1 return unique_slug def save(self, *args, **kwargs): self.slug = self.get_unique_slug() return super(Game, self).save(*args, **kwargs) -
formset : NOT NULL constraint failed: products_productorder.product_id
i have made a formset from formset_factory dynamically when i hit the add button it'll generate a form, with required fields but in the first form even the form is empty and submit the form it doesnt generate any error report to the user (this field is required) , only show NOT NULL constraint failed: products_productorder.product_id also selete2 only work for the first form <script> $(document).ready(function() { $("#product_id").select2(); }); </script> for the rest forms doesnt work for selecting items by typing its names template.html <form method="POST"> {% csrf_token %} <table class="table form-table table-bordered table-sm"> <thead class="text-center"> <tr> <th>products</th> <th>quantities</th> <th></th> </tr> </thead> <tbody> {% for form_data in formset %} <tr class="item"> <td class="col-sm-6" > <label class="text-danger text-bold"> {{form_data.product.errors}}</label> <label for="textarea2"> </label> {{ form.product | add_class:'form-control select2-list' | attr:'id:product_id' }} </td> <td> <label class="text-danger text-bold"> {{form_data.quantity.errors}}</label> {{ form_data.quantity | add_class:'form-control'}} </td> <td> <button type="button" class="btn btn- danger btn-sm remove-form-row" id="{{ formset.prefix }}"> Delete </button> </td> </tr> {% endfor %} <tr> <td> <button type="button" class="btn btn-sm btn-success add-form-row" id="{{ formset.prefix }}"> Add </button> </td> </tr> </tbody> </table> {{ formset.management_form }} <button type="submit">Submit</button> </form> forms.py class ProductOrderForm(forms.ModelForm): product = forms.ModelChoiceField( queryset=Product.objects.filter(active=True),empty_labe l='') class Meta: model = ProductOrder fields = ['product','quantity'] def __init__(self,*args , … -
How do I restart a python app from within the app itself
Got a Django app that has users going through a setup wizard. After the wizard, the app needs to restart for it to pick the necessary settings. The app is run on Ubuntu 18.04 and monitored using supervisord. Ideally am looking to call systemctl restart supervisord.service from the Django app itself. So I've tried import subprocess subprocess.run("systemctl restart supervisord.service") However, this fails with the error: FileNotFoundError [Errno 2] No such file or directory: 'systemctl restart supervisord.service': 'systemctl restart supervisord.service' H -
How to capture parameters from a URL in Django Rest Framwrek to process it in a view
I am new to Django. I am using Django Rest Framework as an Api Rest but I need to generate an endpoint or url that is going to be passed from the frontend (Angular) to get a custom excel, the question is that for example I will pass the following URL: 127.0.0.1:8000/app_prtg/descarga/P79COL01 and I want to capture the value P79COL01 that would be my filtering value to get my excel file, with this parameter I process in a DRF view and I can generate the excel My Url 127.0.0.1:8000/app_prtg/descarga/P79COL01 My Url Definition router.register(r'descarga',MyExampleViewSet) my view to generate the excel and where I should process what comes in the URL and get the value of P79COL01 class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet): queryset = Interfaces.objects.all() serializer_class = InterfaceSerializer renderer_classes = (XLSXRenderer,) filter_class=InterfacesFilter filename = 'my_export.xlsx' -
ValueError: Cannot assign : must be an instance
So I am very new to Django, and I am trying to save a new instance of a model Ovelse, which has a foreign key that points to another model Okt. I have a view that contains a list over all the Okt instances, which links to all the Ovelse instances connected to each Okt. Models.py class Okt(models.Model): def __str__(self): return '{}, uke {}, dag {}'.format(self.sykel_navn, self.sykel_uke, self.sykel_dag) sykel_navn = models.CharField(max_length=8, default="Sykel 1") sykel_dag = models.CharField(max_length=(1), choices=(SYKEL_DAGER)) sykel_uke = models.CharField(max_length=(1), choices=(SYKEL_UKER)) dato = models.DateTimeField('Dato på treningsøkt: ') notater = models.CharField(max_length=400) class Ovelse(models.Model): okt = models.ForeignKey(Okt, on_delete=models.CASCADE) ovelse_type = models.CharField(max_length=2, choices=MUSKELGRUPPE_CHOICES) ovelse_navn = models.CharField(max_length=20) vekt = models.IntegerField(default=0, name='kg') sets = models.PositiveIntegerField(default=2) reps = models.PositiveIntegerField(default=2) def __str__(self): return self.ovelse_navn views.py class OvelseCreateView(generic.CreateView): model = Ovelse template_name = 'trening/add.html' form_class = OvelseForm def form_valid(self, form): form.instance.okt = self.kwargs.get('pk') return super(OvelseCreateView, self).form_valid(form) forms.py class OvelseForm(forms.ModelForm): class Meta: model = Ovelse exclude = ['okt',] fields = ['ovelse_navn', 'ovelse_type', 'kg', 'sets', 'reps'] def __init__(self, *args, **kwargs): super(OvelseForm, self).__init__(*args, **kwargs) self.fields['ovelse_type'].label = "Muskler brukt" self.fields['ovelse_navn'].label = "Navn på øvelsen" self.fields['kg'].label = "Antall kilo" self.fields['sets'].label = "Antall set" self.fields['reps'].label = "Antall reps" When I try to submit the form, I get the error message: Cannot assign "1": "Ovelse.okt" … -
ModelForm has no model class specified with UpdateView
I using ModelForm, UpdateView and Crispy to create User profile setting. But have some problem. Exception Value: ModelForm has no model class specified. If i write like here it will working: views.py class BaseCustomUserCustomize(UserPassesTestMixin, UpdateView): model = CustomUser fields = '__all__' form_class = CustomUserUpdateForm template_name = 'catalog/edit_account.html' success_url = reverse_lazy('catalog:my-account') def test_func(self): obj = self.get_object() return self.request.user.username == obj.username models.py class CustomUserUpdateForm(ModelForm): class Meta: models = CustomUser fields = '__all__' # ['first_name', 'last_name', 'sex', 'avatar', 'birth_date', 'location'] def __init__(self, *args, **kwargs): super(CustomUserUpdateForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.layout = Layout( Field( 'username', 'first_name', 'last_name', 'birth_date', 'sex', 'location', 'avatar', ) ) views.py class BaseCustomUserCustomize(UserPassesTestMixin, UpdateView): model = CustomUser form_class = CustomUserUpdateForm template_name = 'catalog/edit_account.html' success_url = reverse_lazy('catalog:my-account') def test_func(self): obj = self.get_object() return self.request.user.username == obj.username I want to create a base form of user's profile setting like here with crispy form. -
django path showing twice in url bar
i'm using django to make a little weather app for uni and i'm trying to link from the index page to a 'detail' page but in the url the path keeps apearing twice... i've tried rewriting out the entire urls.py page (both of them). I've looked online as well but there dosent seem to be much about this (or i'm not looking in the right places) so when i click on 'more info' for day 1 the url bar shows /day1/day1 instead of just /day1 -
Django is not serving static and media files in development but it is serving in production
I am using windows 10 as OS in development environment and Ubuntu 18.04 (AWS) in production. I deployed my application recently (15 days) but now when I see the django is no more serving media and static files in the development server while it is running and serving perfectly in the production server (with DEBUG=True in both the servers). I am using Nginx server with gunicorn at the production server. I have tried almost every answer in the StackOverflow to counter this issue but it is not working. settings.py: # MEDIA: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') ... STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' # STATICFILES_DIRS = ('static', ) #STATICFILES_DIRS = (os.path.join('static'), ) main_project/urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings # new from django.conf.urls.static import static # new urlpatterns = [ path('', include('stock_management.urls', namespace='stock_management')), path('auth/', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), ] # if settings.DEBUG: # new # urlpatterns += static(settings.STATIC_URL, # document_root=settings.STATIC_ROOT) # urlpatterns += static(settings.MEDIA_URL, # document_root=settings.MEDIA_ROOT) app/urls.py: from django.urls import path, include from .views import * from django.conf import settings app_name = 'stock_management' urlpatterns = [ # Stock: path('', stock_list, name='homepage'), path('stock/', stock_list, name='stock_list'), path('stock/add', stock_create_view, name='add_stock'), path('stock/<pk>/edit', stock_edit, name='stock_edit'), # … -
Django Web app is successfully deployed on Azure App Service Linux but can only see Azure Default Page
I recently published my Django local git repo to the Azure App Service with Python 3.7 runtime. The deployment said it is successful and active but I only see Azure Default Page when I browse it. I can't find any logs anywhere and it shows no signs of errors. How can I solve this ? Thanks and regards, Rachhek.