Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
hidden field changes value when saving form django
This is my model class Person(models.Model): name = models.CharField(max_length=100, blank=True, default='') is_ignore_validations = models.BooleanField(default=False) and this is my form class PersonForm(forms.ModelForm): class Meta: model = Person fields = ['name', 'is_ignore_validations', ] is_ignore_validations = forms.BooleanField(widget=forms.HiddenInput(), required=False) The usage for is_ignore_validations is in the clean_name() function def clean_name(): original_name = self.data.get('name') if not self.initial.get('is_ignore_validations'): pattern = re.compile('^[a-zA-Z]+$') if not pattern.match(original_name): raise ValidationError('name must consist only of letters') return original_name I initiate my form with request.POST, which doesn't have is_ignore_validations. I want it to stay how I've set it manually in the DB, but when I use form.save() it always changes to False. So firstly, how do I keep is_ignore_validations data in DB always the same? Secondly, is the usage in clean_name of the variable from initial best practice - self.initial.get('is_ignore_validations')? -
Having trouble updating python from 2.7 to 3.9 on MacBook
I'm a newbie to python and am having a really rough time trying to update the python version on my MacBook. I use a MacBook with macOS Monterey and with python installed over a year ago. When I type python --version in the terminal, the version printed out is v2.7. I'm trying to self-learn Django for web development, and need python version 3.9. I did a google search and found a site that gives a step by step tutorial on getting up and running with Django. As instructed on this site, I tried running "brew install python3" but I get the following message: "Error: homebrew-core is a shallow clone. To brew update, first run: ----and some info here---- What is confounding is that even though I get an error, the terminal then shows hundreds of errors before the process finally ends. Could someone provide guidance on how I (being a noob) can resolve this mess and update python to the latest version (3.9), so I can do an install of Django? -
How Django widget initiates from django form classs?
I am trying to add CKEditor to django form flields . I saw that there is a item that is widget . Whenever CKEditor is added as widget I saw that the field is assigned with a object of ckeditor . So what I did is I have written a decorator that modifies fields and adds widget's value is CKEditorWidget(). But when I am updating the widget its not reflecting on browser. My question is when the widget initiates ? do I need to do anything like call any function after updating the field.widget ? class CompanyForm(forms.ModelForm): # description = forms.CharField(widget=CKEditorWidget(), required=False) system_description = forms.CharField(widget=CKEditorWidget(), required=False) system_focus = forms.CharField(widget=CKEditorWidget(), required=False) class Meta: model = Company fields = ('description', 'system_description', 'system_focus') -
Static is not loading properly after cloning a Django project from git
Actually, I am hosting a project to a domain using a Linode server. The Project is on Bitbucket. I have tried all the methods static root static dirs and collect static but nothing works half of the CSS is loading but not left Static. STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR / 'static/')] #STATIC_ROOT = os.path.join(BASE_DIR, 'static/') -
How can I connect to the same github repository for heroku and Ditigitalocean?
Is it possible to do that connection??? I have a project which I want to run on heroku at the same time on Digitalocean. I tried it but heroku returns an error if I remove the Procfile, which Digitalocean does not require. DO works if I remove the Procfile but heroku errors, and vieversa. -
Django Admin unable to create custom view with get_urls
I am following the instructions in the following video here on creating a CSV upload on the admin site but have ran into an issue at about 13:50. I am trying to create a custom view but whenever I click on the link, instead of going to the new page it returns to the main admin page with the following error at the top. Crime with ID “upload-csv” doesn’t exist. Perhaps it was deleted? I'm pretty sure I've done the code the same as in the video, but here are a couple of code snippets in case I missed something. class CrimeAdmin(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() new_urls = [path('upload-csv/', self.upload_csv),] return new_urls + urls def upload_csv(self, request): return render(request, "admin/csv_upload.html") And here is the HTML. {% extends 'admin/base.html' %} {% block content %} <div> hello world </div> {% endblock %} What exactly is causing the issue here? I can't figure out if I did something in the code wrong or there is something I was supposed to that wasn't in the video that I forgot? -
is there a way to show my Django code in github so people can try it?
I currently uploaded my first Django project to github and made a url thinking this will show my project on a github webpage just like it does for html and css but this wasn't the case it just shows the readme file instead. -
DRF Serializer logic to transform data
In a word of introduction - I'm using the react-table library and I want to display in it (if any) all PZItems and no Item or just Item (if there are no PZItems). I decided that it would be the best solution to display the data, as I couldn't otherwise design a serializer without duplicating the data anyway. React-Table doesn't like data in diffrent form, at least I failed trying to during the tests. I spent the last hours trying to flatten the serializ data which turned out to be a dead end. I was able to write code in JS that transforms serializerdata into the form I need. However, this is not the best solution... Below are simplified models and the rest of the code. How to write a serializer to match the given form? & How to display a table using a react-table with the current data. The second question is because I'm not sure my approach to the problem is right. However, executing some type of header in the middle of the list in the react-table for an Item that has a PZItem is beyond my abilities. Models class PZItem(models.Model): item = models.ForeignKey(Item, related_name='pz_items', verbose_name="Przedmiot", on_delete=models.CASCADE) quantity_available_to_order … -
How to solve the error when dummy data gets stored in Django database with its id as none and all values as null
I had made this form in Django which takes some data and when a save button is clicked it saves it to the database. It stores the data that I give, but I noticed that every time I refreshed the page that contained the form it would automatically save an object with the Id as none and all values set to null. I wanted to know how to write a function that says the form only submits to the database when the save submit button is clicked and not when reloading the page and making a dummy object in the database. -
How to set a derived attribute field of a django model in a JSON fixtures file?
The model would look something like this: class MyModel(models.Model): primary_key = models.CharField(blank=False, unique=True) created_at = models.DateTimeField(auto_now_add=True, blank=False) And in the fixtures file for unit tests: [ { "model": "app.model", "pk":1, "fields" : { "primary_key" : "Idetifier1", "created_at": {NO IDEA} } } ] Note that if left blank I get NOT NULL violations because it hasn't been set automatically as it would have when using .create() Perhaps this can't be done? Is this a bad use of django fixtures? Thanks! -
How to retrieve information from database to html template using built in usermodel django.contrib.auth
This is my html part where i want to retrieve it but it wont work -
Capture image with opencv and upload to django database
I can capture image using opencv in django app but don't know how to load it to database model. I am new to django. Thanks for help -
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 …