Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to hide/remove a particular data from the "NETWORK" tab when we inspect element on a webpage
enter image description here I am working on React project and want to display the scores of an assessment, but the score should be anonymous(that is we should not be able to see the score of individual member. we Should just see the overall scores of all members without the score being traced to their name). I want to hide the 'score' response from the network tab so that it is not accessible on the frontend. Is there a way I can do it? Thanks in advance . -
Can you add a python script to a webpage made with django?
I want to add a python program to a webpage made with django. Is there any way I can do that? -
MEDIA_URL not displaying PDF links
There are pdfs in my media folder, but this won't display them in my HTML. I've checked other posts, but nothing works <h1 class="my-4">Batch Records</h1> <div class="row"> {% if MEDIA_URL%} <div class="col-lg-4 col-md-6 col-sm-12 pb-4"> <p>Uploaded to:<a href="{{ MEDIA_URL }}">{{ MEDIA_URL }}</a></p> <a class="btn btn-dark my-4" href="/">Return to Homepage</a> {% else %} <p>No records added.</p> {% endif %} </div> SETTINGS.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') VIEWS.py def upload(request): if request.method == 'POST' and request.FILES['upload']: upload = request.FILES['upload'] fss = FileSystemStorage() file = fss.save(upload.name, upload) file_url = fss.url(file) return render(request, 'website/upload.html', {'file_url': file_url}) return render(request, 'website/upload.html') URLS.py from django.contrib import admin from django.urls import path, include from inventory import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path("br", views.upload, name="upload") ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Modify Django migrations file, or use --fake flag?
I am new to Django and I am working on renaming some old tables. I am also taking some fields that already exist in a few tables, and making them foreign keys. After making the changes, and running makemigrations I went into the newly created migrations file and noticed that Django is attempting to make a new model. Then it is trying to delete the old model. I think the issue is it is attempting to create a new model before deleting the old model. If I try to run migrate right now it throws me an error saying: django.db.utils.ProgrammingError: ('42S01', "[42S01] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]There is already an object named 'tblFailureTypes' in the database. (2714) (SQLExecDirectW)") My migrations file looks like: from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('foo', '0001_initial'), ] operations = [ migrations.CreateModel( name='FailureType', fields=[ ('id', models.AutoField(db_column='FailureID', primary_key=True, serialize=False)), ('failure_type', models.CharField(db_column='Failure Type', max_length=255, null=True)), ], options={ 'db_table': 'tblFailureTypes', 'managed': True, }, ), migrations.DeleteModel( name='FailureTypes', ), I have seen two possible workarounds: Use the --fake flag when running migrate, but I have seen a lot of comments that this can cause problems later down the road. (I am also thinking … -
Django - Foreign Key on non-unique field
Consider two models: from django.db import models class File(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=256, unique=False) class Comment(models.Model): id = models.AutoField(primary_key=True) file_name = models.ForeignKey(to=File, on_delete=models.CASCADE, to_field="name") text = models.CharField(max_length=1000, unique=False) and some data: f1 = File.objects.create(id=1, name="a.xlsx") f2 = File.objects.create(id=2, name="a.xlsx") f3 = File.objects.create(id=3, name="b.xlsx") c1 = Comment.objects.create(id=1, file_name="a.xlsx", comment="Comment 1") c2 = Comment.objects.create(id=2, file_name="a.xlsx", comment="Comment 2") c3 = Comment.objects.create(id=2, file_name="b.xlsx", comment="Comment 3") From the above: f1 is associated to two comments: c1 and c2 f2 is also associated to two comments: c1 and c2 f3 is associated to one comment: c3 But according to this, ForeignKey.to_field requires File.name to be unique but that's not the case. How can I achieve this relationship without creating any intermediary tables? So ideally: f1.comments would return c1 and c2 c1.files would return f1 and f2 etc -
Django Forms/Model ValueError: Cannot Assign xxx, must be a xxx instance
I am currently working with Django forms. One field of the form is a choice field that has choices for different flavors of ice cream that are in the database. The error looks like : ValueError at /orderentry/ Cannot assign "'CHOCOLATE'": "orderInfo.order_Item_Flavor" must be a "flavor" instance. Here is any relevant code I can think of: orderentry.forms.py class customerOrder(forms.ModelForm): order_Item_Flavor = forms.ChoiceField(choices=flavor.flavor_Choices) half_Pint_Count = forms.IntegerField() one_Quart_Count = forms.IntegerField() pint_Count = forms.IntegerField() half_Gallon_Count = forms.IntegerField() gallon_Count = forms.IntegerField() class Meta: model = orderInfo fields = ('order_Item_Flavor','half_Pint_Count', 'one_Quart_Count', 'pint_Count', 'half_Gallon_Count', 'gallon_Count',) inventory.models.py class flavor (models.Model): class Meta: verbose_name = "Flavor" verbose_name_plural = "Flavors" flavor_Choices = [('CHOCOLATE','chocolate'),('VANILLA', 'vanilla'),('COOKIESNCREME', 'cookiesncreme'), ('STRAWBERRY', 'strawberry')] flavor = models.CharField(max_length=100, choices = flavor_Choices) def __str__(self): return '%s Flavor' % self.flavor orderentry.models.py class orderInfo (models.Model): class Meta: verbose_name = "Order Information" verbose_name_plural = "Order Information" order_Item_Flavor = models.ForeignKey('inventory.flavor', on_delete=models.CASCADE) half_Pint_Count = models.IntegerField(default=0) one_Quart_Count = models.IntegerField(default=0) pint_Count = models.IntegerField(default=0) half_Gallon_Count = models.IntegerField(default=0) gallon_Count = models.IntegerField(default=0) cost = models.IntegerField(default=0) customer = models.ForeignKey(customerInfo, on_delete=models.CASCADE, default = 0) def __str__(self): return '%s, Half Pint: %s, Quart: %s, Pint: %s, Half Gallon: %s, Gallon: %s, $%s' % (self.order_Item_Flavor, self.half_Pint_Count, self.one_Quart_Count, self.pint_Count, self.half_Gallon_Count, self.gallon_Count, self.cost) orderentry.views.py def getCustomerOrder(request): form = customerOrder(request.POST) if request.method == 'POST': if … -
Django - multi-level table challenge
I'm new to Django, but an older programmer ;o) I've managed to create a functionally working site that has 5 tables. Where each one is a 1-to-M relationship to the one below it. Also created the breadcrumb at the top of each page. I'm using htmx to allow interaction with the 0 to many records under the parent record directly above. Two challenges, how to traverse all 5 tables to Display all data for a given A record and/or create a report for a given A record and Create a navigation sidebar or similar for the first 3 levels to provide visibility of what entries you've got Example of potential structure -> A -> B -> C -> D -> E -> D -> E -> B -> C -> D -> E -> E -> D -> E looking for some thoughts or any pointers to examples -
django rest framework: Get nested representation of child elements
I have a tree of items which reference each other as parent/children. Now I want to get them through the API as nested objects to minimize the requests. My problem is that I can't initiate the serializer class from within itself (obviously)... Is there a way to do this? Model: class Item(models.Model): name = models.CharField(max_length=128) dashboard = models.ForeignKey(Dashboard, on_delete=models.CASCADE) config = models.JSONField(null=True, blank=True) parent = models.ForeignKey("Item", on_delete=models.CASCADE, related_name="children", null=True, blank=True) previous = models.OneToOneField("Item", related_name="next", null=True, blank=True, on_delete=link_previous_item_on_delete) Serializer: class ItemSerializer(serializers.HyperlinkedModelSerializer): children = ItemSerializer(many=True, read_only=True) class Meta: model = Item fields = ("name", "dashboard", "config", "children") -
Is there a way to use a temporary non-field variable in factoryboy?
I am defining some factories for testing my e-commerce store. I have created a Faker provider that can return, for instance, a dictionary containing all the data for a random product. I want to then use that dictionary to populate the fields in my factory. This is because the data in the dictionary is coherent. I don't want to create a factory with data that is not coherent e.g. a Product with name: "Short sleeve t-shirt" and then description: "Beautiful, comfortable shoes." Is there a way that I can implement something similar to class ProductFactory(factory.django.DjangoModelFactory): temporary_product_dict = fake.product_dict_from_provider() name = temporary_product_dict["name"] description = temporary_product_dict["description"] category = temporary_product_dict["category"] ... class Meta: model = models.Product When I do this exact thing, I get an error which tells me that temporary_product_dict is not an attribute of the Product model. -
Load values from Models.py into Views.py
I am trying to create a page that allows a user to change certain CSS variables in the Django admin page and I am having some issues pulling a single value from the models.py and assigning it to a variable in my views.py. Assigning the colors inside the Django admin page works but I am unsure of how I would go about setting the linkcolor variable in views.py to the link_color variable in models.py. views.py from django.shortcuts import render from django.http import HttpResponse from .models import cssEditor # Create your views here. def index(request): linkcolor = "#000" # Grab link_color from models.py here linkfont = "Brush Script MT" # Grab link_font from models.py here linkbc = "whitesmoke" # Grab link_bc from models.py here return render(request, "SocialLinks/index.html", {"linkcolor":linkcolor, "linkfont":linkfont, "linkbc":linkbc}) models.py from django.db import models # Create your models here. class cssEditor(models.Model): link_color = models.CharField(max_length=7, default="000000") link_font = models.CharField(max_length=15, default="Brush Script MT") link_bc = = models.CharField(max_length=7, default="#F5F5F5") admin.py from django.contrib import admin from SocialLinks.forms import * # Register your models here. @admin.register(cssEditor) class cssEditor(admin.ModelAdmin): form = cssForm forms.py from django.forms import ModelForm from django.forms.widgets import TextInput from SocialLinks.models import * class cssForm(ModelForm): class Meta: model = cssEditor fields = "__all__" widgets … -
how to auto set the topic of a comment to the same topic with the post
i want to be able to create comments by clicking on the comment link under the post, every post has a topic, but i'm unable to get the comments under a specific post, so i thought to add the topic as well for more functionality, but i'm finding it hard to automatically assign the topic based on what post i'm commenting on my views.py the pk is set as the post.id def comment(request, pk): form = commentform() context = { 'form' : form } if request.method == 'POST': form = commentform(request.POST) if form.is_valid(): forms = form.save(commit=False) forms.posts = post.objects.get(id=pk) forms.owner = request.user forms.topics = topic.objects.get(id=pk) forms.save() return redirect('home') return render(request, 'base/comment.html', context) my models.py class comments(models.Model): topics = models.ForeignKey(topic, on_delete=models.CASCADE, SET_NULL=True, null=True) created = models.DateTimeField(auto_now=True) posts = models.ForeignKey(post, on_delete=models.CASCADE) owner = models.ForeignKey(User, on_delete=CASCADE) comment = models.TextField(max_length= 500) def __str__(self): return str(self.comment) class post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) Topic = models.ForeignKey(topic, on_delete=models.CASCADE) post = models.TextField(max_length=500) created = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.post}' my forms.py class commentform(ModelForm): class Meta: model = comments fields = ['comment'] -
Django.db.utils.DataError: invalid input syntax for type integer: "Build"
I have thee model class, with manytomany field, and i use postegresql as base, problem is when I migrate my models terminal shows : how can i fi it ? File "C:\Users\zura\Desktop\personalization\manage.py", line 21, in <module> main() File "C:\Users\zura\Desktop\personalization\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\zura\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management_init_.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\zura\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management_init_.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\zura\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.DataError: invalid input syntax for type integer: "Build" class Person(models.Model): name = models.CharField(max_length=50, null=True) def __str__(self): return self.fullname class Features(models.Model): name = models.CharField(max_length=30, null=True) feature = models.ManyToManyField(Person, through='Enrollment') def __str__(self): return self.name class Enrollment(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE, null=True) job = models.ForeignKey(Features, on_delete=models.CASCADE, null=True) def __str__(self): return self.person.fullname -
Set a limit of submits forms with the same object
I'm working on a school project where there are activities with different limits of people they can have plaatsen_beschikbaar. Also, students can only apply for one activity beperk_aanmelden. models.py class Activiteit(models.Model): titel = models.CharField(max_length=64) docent = models.CharField(max_length=32) icon = models.ImageField() uitleg = models.TextField() plaatsen_beschikbaar = models.IntegerField() def beperk_aanmelden(value): if Aanmelden.objects.filter(studentnummer=value).count() >= 1: raise ValidationError('Student heeft al de maximale aanmeldingen') else: return value class Aanmelden(models.Model): naam = models.CharField(max_length=32) studentnummer = models.IntegerField(validators=[beperk_aanmelden,]) klas = models.ForeignKey(Klas, on_delete=models.CASCADE, default=None, blank=True) activiteit = ForeignKey(Activiteit, on_delete=models.CASCADE, default=None, blank=True) Aanmelden is the model to apply to an activity. views.py def home(request): activiteiten = Activiteit.objects.all() form = AanmeldenForm() if request.method == 'POST': form = AanmeldenForm(request.POST) if form.is_valid(): form.save() Aanmelden.objects.get() return render(request, 'home.html', { 'activiteiten': activiteiten, 'form':form, }) I need to do a function that discounts the available places in an activity and when it reaches 0 it doesn't allow any more submits to that activity. It's literally the last function from my backend I have to do to finish this and it's gotta be done by monday so how can I do this? -
Proper way to use clean_email in DRF
I've defined the model as pass and I'm using the UserSerializer to validate the password and create a new user. What I'm trying to do is that people can only SignUp if it's not with a known provider such gmail.com, outlook.com, live.com, etc. I know in DJango there is the clean_emailfeature that would help with something like this: class SignUpForm(forms.ModelForm): class Meta: model = SignUp fields = ['username', 'email'] def clean_email(self): email = self.cleaned_data.get('email') email_base, provider = email.split("@") domain, extension = provider.split('.') Is there any similar functionality in Django Rest Framework? I've looked up but couln't find anything -
Django response - if POST = None leave blank key, value pair from jsonresponse
the below form + view works fine forms.py class FormGlobalSettings(forms.Form): global_font_family = forms.TypedChoiceField(required=False, label='Font Family', choices=choices_font_family, empty_value=None) views.py def main_view(request): if request.method != 'POST': form_global_settings = FormGlobalSettings() else: form_global_settings = FormGlobalSettings(data=request.POST) if all([form_global_settings.is_valid()]): cleaned_data = form_global_settings.cleaned_data nested_data = {"fontFamily": cleaned_data3['global_font_family']} return JsonResponse(nested_data) return render(request, 'pbi_theme_app/index.html', {'form_global_settings': form_global_settings}) Output is: {"fontFamily": "Arial"} However, what I am trying to achieve is, that sometimes the POST request is blank/empty/null, as the user doesn't want to have any value in this field. The choices for the global_font_family are set up in this manner: choices_font_family = [(None, ""), ("Arial", "Arial"), etc..] Meaning that the if the user leaves the field empty, it results into None. This results into having it in the json as null: {"fontFamily": null} Now what I am trying to achieve, and because I have hardcoded "fontFamily" into the jsonresponse, I want the whole key, value pair to be gone if the user decides to have the field empty, meaning that the whole key, value pair "fontFamily: null is gone from the jsonresponse. To summarize: I need to somehow make the key in the json dynamic, and when the POST request is empty, I want to leave the whole key, value pair … -
Django ModuleNotFoundError: No Module named 'localflavor'
I am getting a perplexing ModuleNotFound error with a project where I am attempting to start a new app. This has not been a problem until just now. When I run: python manage.py startapp newapp I get the following error: Traceback (most recent call last): File "/Users/mainuser/Desktop/ohive/manage.py", line 22, in <module> main() File "/Users/mainuser/Desktop/ohive/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Users/mainuser/.pyenv/versions/3.9.2/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'localflavor' (ohive) bash-3.2$ python manage.py startapp tenant_howto /tenant_customapps/intranet Traceback (most recent call last): File "/Users/mainuser/Desktop/ohive/manage.py", line 22, in <module> main() File "/Users/mainuser/Desktop/ohive/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File … -
No module named 'social_django' but 'social-auth-app-django' is installed
Summary of Issue I am creating a Django project and attempting to setup Auth0 integrations. Per Auth0's documentation, I installed the social-auth-app-django library which then went and also installed social-auth-core. So please note that both these libraries are installed. Here is my py -m pip list output proving such: Package Version ---------------------- --------- asgiref 3.4.1 certifi 2021.10.8 cffi 1.15.0 charset-normalizer 2.0.7 colorama 0.4.4 cryptography 35.0.0 defusedxml 0.7.1 Django 3.2.9 ecdsa 0.17.0 idna 3.3 oauthlib 3.1.1 pip 21.3.1 pyasn1 0.4.8 pycparser 2.21 PyJWT 2.3.0 python-dotenv 0.19.2 python-jose 3.3.0 python-social-auth 0.3.6 python3-openid 3.2.0 pytz 2021.3 requests 2.26.0 requests-oauthlib 1.3.0 rsa 4.7.2 setuptools 57.4.0 six 1.16.0 social-auth-app-django 5.0.0 social-auth-core 4.1.0 sqlparse 0.4.2 urllib3 1.26.7 As you can see, I'm running Django 3.2.9. I am also using Python 3.10. After following all of Auth0's steps, I went to run py manage.py migrate and receive the following ending error message: ModuleNotFoundError: No module named 'social_django' What I have tried I have tried uninstalling and reinstalling the social-auth-app-django and social-auth-core libraries multiple times. I have also tried installing the libraries individually instead of just installing social-auth-app-django. I have also tried installing social-auth-app[django] (using brackets). Nothing has worked. Every post I can find online is telling the … -
Django field DateField with year only or with year and month etc. with filtering
I have a question regarding the DateField. Is there any possibility for the field to accept only a year or a year and a month? I want to add an incomplete date to the database and filter by this field. I download books from API and the date is not always full there. I want to download the results, save them to the database and display a list of these objects on the page with an incomplete date or a complete date. -
Django - constructing multi column indexes
Say we have a model that looks thus: class Entry(models.Model): """Users will query for entries with various combinations of filters""" date_created = models.DateTimeField(auto_now_add=True) important = models.BooleanField(default=False, null=False) urgent = models.BooleanField(default=False, null=False) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) What is the correct way to create indexes that will cater for any combination of the above fields in filters? E.g. .filter(date_created__year='2021', important=False, user=1) My first thought was the below but I have a suspicion I'm doing something wrong here... class Meta: indexes = [models.Index(fields=['-date_created']), models.Index(fields=['-date_created', 'important']), models.Index(fields=['-date_created', 'important', 'urgent']), models.Index(fields=['-date_created', 'important', 'urgent', 'user']), models.Index(fields=['-date_created', 'user']), models.Index(fields=['....etc...'])] I read through the Django documentation and noted their use of the include argument that was introduced in Django 3.2, but was unable to find useful examples of it's use. Would it work in my situation? class Meta: indexes = [models.Index(fields=['-date_created'], include=['important', 'urgent', 'user'])] Thank you -
get list of items, which were passed from python file (Django) to html, from html to Javascript, which is on the same page
my python code: def index(request): body=list(Body.objects.all()) loads=list(Load.objects.all().order_by('length')) badLoads=[] goodLoads=[] for load in loads: if load.length>body[0].length or load.width>body[0].width or load.mass>body[0].mass: badLoads.append(load) else: goodLoads.append(load) goodLoadsLength=len(goodLoads) context={ 'body':body[0], 'loads':loads, 'badLoads':badLoads, 'goodLoads':goodLoads, 'goodLoadsLength':goodLoadsLength, } return render(request,'index.html',context) html code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Positioning of objects</title> </head> <body> <div> {% if body %} <p>body length: {{ body.length }}, body width: {{ body.width }}, body height: {{ body.height }}, body max mass, which can be taken: {{ body.mass }}</p> {% else %} <p>No parameters found</p> {% endif %} </div> <div> {% if loads %} <ul> {% for load in loads %} <li>load id: {{ load.id }}, load length:{{ load.length }}, load width: {{load.width}}, load height: {{load.height}}, load mass: {{load.mass}}</li> {% endfor %} </ul> {% else %} <p>No loads are available.</p> {% endif %} </div> <div> {% if goodLoads %} <ul> {% for goodLoad in goodLoads %} <li>load id: {{ goodLoad.id }}, load length:{{ goodLoad.length }}, load width: {{goodLoad.width}}, load height: {{goodLoad.height}}, load mass: {{goodLoad.mass}}</li> {% endfor %} </ul> {% else %} <p>No loads are available.</p> {% endif %} </div> <div> {% if loads %} <ul> {% for badLoad in badLoads %} <li>load id: {{ badLoad.id }}, … -
(Django) include does not import other apps' urls
In my Django project I have 2 apps: core and books. In my core/urls.py, I use python include('books.url') to import the urls from books/urls.py, but I keep getting this error I have been having this issue now that's bugging me. I had a workaround for it, though I really want to fix this. core/urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include # local urlpatterns = [ path('/', include('books.urls')), path('admin/', admin.site.urls), ] books/urls.py from django.contrib import admin from django.urls import path # local from graphene_django.views import GraphQLView from books.schema import schema urlpatterns = [ path('graphql/', GraphQLView.as_view(graphiql=True, schema=schema)), ] As suggested by SO, I have: put books.urls inside the single quotes ' ' placed the path('/', include('books.urls')) on top switch from from django.urls import include to from django.conf.urls import include The only workaround I have is place all urls into the core/urls.py, but that seems too chunky in the long run. I don't get why include works for everyone but not me! Could you help me with this issue? Thank you! -
Django POST data to via form and redirect to page with POST data
I have a Django form, that once the data has been submitted I'd like to redirect to another page where the data will be displayed. I'm having trouble as I don't know how to retrieve the Foreign Key until the form has been submitted Form class addEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(addEventForm, self).__init__(*args, **kwargs) class Meta: model = Event fields = '__all__' View class addEventView(LoginRequiredMixin,View): template_name = 'pages/add_event.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request, *args, **kwargs): form = addEventForm(request.POST) if form.is_valid(): form.save() data = {"success": "successfully added"} else: data = {"error": form.errors} return JsonResponse(data, safe=False) How do I redirect but pull in the data from the POST? Thanks -
Multiple forms with bootstrap modal in one single create view in Django
I have 5 forms: MyForm, EducationForm, ExperienceForm, RecommendationForm, OtherDocumentsForm. 1st is Main form and others (EducationForm, ExperienceForm,RecommendationForm,OtherDocumentsForm) should be in bootstrap modal. During filling the main form(MyForm), I also have to fill other forms with bootstrap modal and Finally all of them should be attached to Main form. I connected them other forms with Foreign key to MyForm. I stucked in this situation. Could anyone knows how to get data from bootstrap and connect them in one view? MyForms class MyForm(forms.ModelForm): class Meta: model = UserForm_uz fields = 'all' class EducationForm(forms.ModelForm): class Meta: model = Education_uz fields = 'all' class ExperienceForm(forms.ModelForm): class Meta: model = Experience_uz fields = 'all' class RecommendationForm(forms.ModelForm): class Meta: model = Recommendation_uz fields = 'all' class OtherDocumentsForm(forms.ModelForm): class Meta: model = OtherDocuments fields = 'all' My models: # Create your models here. language_choices = [('1', 'Билмайман'), ('2', 'Ёмон'), ('3', 'Лугат ёрдамида'), ('4', 'Ўртача'), ('5', 'Яхши'), ('6', 'Жуда яхши'), ] approve_choices = [('Yes', 'Ха'), ('No', 'Йўк')] agreement_choices = [('Yes', 'Ха'), ('No', 'Йўк')] class UserForm_uz(models.Model): rasm = models.ImageField(upload_to='rasmlar',null=True,blank=True) lastName = models.CharField(max_length=200) firstName = models.CharField(max_length=200) middleName = models.CharField(max_length=200) birthData = models.DateField() nation = models.CharField(max_length=50) birthPlace = models.CharField(max_length=250) marriage_status = models.CharField(max_length=20) children = models.CharField(max_length=20) militaryResp = models.CharField(max_length=150) language_uzbek = models.CharField(choices=language_choices,max_length=150) … -
How to get data from User related model to template
I have Profile model in addition to native User model. Since user is logged in, I need to load avatar image to all pages in frontend. I need something like this: {% if request.user.is_authenticated %}<img src={{ profile.avatar }}>{% endif %} How I can do that? class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='media/avatar/', verbose_name='Аватар', default='media/avatar/default_avatar.jpg') @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
Setting a lazy reference to a django serializer class
I have two models which has a field reference to each other. Both were in seperate files, but i decided to put them in a single file to avoid circular import bugs. However, unlike making a lazy reference to a django model class, i can't seem to make it work here class QuestionAnsweringModelResultsSerializer(ModelSerializer): answers = AnswerAnsweringModelResultsSerializer(many=True) images = QuestionAnsweringModelImagesResultsSerializer(many=True) written_answer_marking_settings = QuestionMarkingSettingsSerializer() parent_question = QuestionResultsSerializer() procedural_answers = ProceduralAnswerAnsweringSerializer(many=True) # the field below makes reference to the class below fill_in_the_blanks_answers = FillInTheBlanksAnsweringModelResultsSerializer(many=True) class Meta: model = QuestionAnsweringModel fields = '__all__' class FillInTheBlanksAnsweringModelResultsSerializer(ModelSerializer): # the field below makes reference to the class above question = QuestionAnsweringModelResultsSerializer() class Meta: model = FillInTheBlanksAnsweringModel fields = '__all__' I get the error a class is not defined error where class is the name of the Serializer Class