Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use multiple templates in Generic ListView?
I have some ListViews implemented seperately with different template_names with similar model,How can i use implement them in one single List view that can take multiple templates? Views.py class ManagerOpenedTicketView(LoginRequiredMixin,TemplateView): template_name = 'app/pm_open_tickets.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tickets'] = Ticket.objects.filter(status = 'Opened',created_by = self.request.user) return context class ManagerCompletedTicketView(LoginRequiredMixin,TemplateView): template_name = 'app/pm_completed_tickets.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tickets'] = Ticket.objects.filter(status = 'Completed',created_by = self.request.user) return context class ManagerAcceptedTicketView(LoginRequiredMixin,TemplateView): template_name = 'app/pm_accepted_tickets.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tickets'] = Ticket.objects.filter(status = 'Accepted',created_by = self.request.user) return context -
How to serve static files (like images) in a combined django-react application
This is the first web application I'm developing by combining django and react, in fact react is new to me. Please if my approach is wrong I'm open for correction. When developing with purely django, I find no difficulty with static and media files. I understand the elements involved are the media root and static root, respectively. In that case, all I need to do is to specify the static/media root in the settings.py in the django app as shown below: settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/images/' urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \ + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) However, when I combine django and react the configuration changes since django is configured to look at index.html file in react, in which case an additional element called STATICFILES DIRS is added to the seetings.py file to specify the path to react index.html. In fact, my django app configuration looks like this when I combine django and react: settings.py STATICFILES_DIRS = [os.path.join(BASE_DIR, 'build/static')] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/images/' urls.py urlpatterns = [ ... re_path(r'^.*', TemplateView.as_view(template_name='index.html')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, … -
Data from database not showing Django
I am trying to get for people to upload their answers for for a specific assignment and trying to show them the instructions from the django database. But it is not working. Not sure why. Here's some of the code I have: html: <div class="main"> {% for a in assignment %} <div> <div><h1>{{a.title}} </h1><p>{{a.due_date}}</p></div> <div> <h2>{{a.instructions}}</h2> <h6 style="color: grey;">{{a.points}}</h6> </div> </div> {% endfor %} </div> views.py: from django.shortcuts import render from django.contrib.auth.decorators import login_required from ******.models import Assignment ..... @login_required def assignments_page(request): assignments = Assignment.objects.order_by('id') context = {'assignment': assignments} return render(request, 'samgau_page/assignments.html', context) models.py: from django.db import models # Create your models here. class Assignment(models.Model): groups = ( 'your choices' ) title = models.CharField(max_length=200) assignment_image = models.ImageField(null=True, blank=True, upload_to="images/") instructions = models.TextField(max_length=1000) due_date = models.DateTimeField(blank=True) points = models.IntegerField(default=100) group = models.CharField(max_length=10000, choices=groups) def __str__(self): return self.title And the picture below is the admin website -
How do I create a Django migration for my ManyToMany relation that includes an on-delete cascade?
I'm using PostGres 10, Python 3.9, and Django 3.2. I have set up this model with the accompanying many-to-many relationship ... class Account(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... crypto_currencies = models.ManyToManyField(CryptoCurrency) After generating and running Django migrations, the following table was created ... \d cbapp_account_crypto_currencies; Table "public.cbapp_account_crypto_currencies" Column | Type | Modifiers -------------------+---------+------------------------------------------------------------------------------ id | integer | not null default nextval('cbapp_account_crypto_currencies_id_seq'::regclass) account_id | uuid | not null cryptocurrency_id | uuid | not null Indexes: "cbapp_account_crypto_currencies_pkey" PRIMARY KEY, btree (id) "cbapp_account_crypto_cur_account_id_cryptocurrenc_38c41c43_uniq" UNIQUE CONSTRAINT, btree (account_id, cryptocurrency_id) "cbapp_account_crypto_currencies_account_id_611c9b45" btree (account_id) "cbapp_account_crypto_currencies_cryptocurrency_id_685fb811" btree (cryptocurrency_id) Foreign-key constraints: "cbapp_account_crypto_account_id_611c9b45_fk_cbapp_acc" FOREIGN KEY (account_id) REFERENCES cbapp_account(id) DEFERRABLE INITIALLY DEFERRED "cbapp_account_crypto_cryptocurrency_id_685fb811_fk_cbapp_cry" FOREIGN KEY (cryptocurrency_id) REFERENCES cbapp_cryptocurrency(id) DEFERRABLE INITIALLY DEFERRED How do I alter my field relation, or generate a migration, such that the cascade relationship is ON-DELETE CASCADE? That is, When I delete an account, I would like accompanying records in this table to also be deleted. -
Django acces <table> content POST
im creating an app where the user selects an Excel file and i create a dataframe out of that file. After that I add a checkbox to the dataframe and render the DataFrame to HTML Table. Now the user should be able to select individual rows and save the corresponding data into the database. This is my view: def mmuebersicht_view(request): if request.method == 'POST': context = {} form = request.POST.get('dropdown') stueckliste_data_file = '../prozessmapping/media/' + form df = read_file(stueckliste_data_file) df.insert(0,'A','<input type="checkbox">') context['result'] = df.to_html(index=False,escape=False) return render(request, 'web/mmuebersicht.html', { 'result': context['result'], }) I display the Table with the following: <form method="post" id="tableForm"> {% csrf_token %} {{ result|safe }} <button type="submit" form="tableForm" class="btn">MaterialMatrix Anlegen</button> </form> The output is shown in the following picture: Picture of HTMl table I want to achieve that the selected rows of the user are stored in the database. I have two Problems: How can i acces the Data of the table when i make a POST ? how can i filter the data and save only selected rows ? I tried to get the content of the Table via Name tag. But i have found out that the Name tag is not an allowed attribute of in HTML5. -
Why is this code throwing a syntax error?
I'm just learning Django and tried to execute this example in the shell from .models import model_name obj_or_queryset = model_name.obejcts.<method_name_from_the_table>() It fails with several syntax errors. File "", line 1 from .models import model_name obj_or_queryset = model_name.obejcts.<method_name_from_the_table>() ^ SyntaxError: invalid syntax -
Django database tables
i would like to get some help setting up my db tables relationships. My main issue is that I have a many to many relationships between trucks and locations and then I have a third model of sales were for each sale I need to add the location and the truck but I'm confused how to set all that up, thanks in advanced -
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.