Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why DRF suggest to override HTTP methods in serializers?
Since all the HTTP methods are implemented in Viewsets, isn't it make sense to override them in child Viewsets? why Django rest framework has given a lot of examples of overriding these methods in serializers? Is there any trade-off overriding these methods in serializers vs viewsets? -
Why Getting (user.models.DoesNotExist: CustomUser matching query does not exist.)?
I have create two models CustomUser inheriting AbstractUser and UserProfile, and there is OneToOne relation between them. then i run the following command:- python manage.py makemigrations python manage.py migrate python manage.py createsuperuser When i run the command for createsuperuser, i got error as bellow:-(model are posted in the end..) PS C:\Users\akcai\OneDrive\Desktop\deep_Stuffs\git_cloned\PollingApplication> python manage.py createsuperuser Email: admin@gmail.com Name: admin Username: admin Password: Password (again): The password is too similar to the username. This password is too short. It must contain at least 8 characters. This password is too common. Bypass password validation and create user anyway? [y/N]: y profile create too.. Traceback (most recent call last): File "C:\Users\akcai\OneDrive\Desktop\deep_Stuffs\git_cloned\PollingApplication\manage.py", line 22, in <module> main() File "C:\Users\akcai\OneDrive\Desktop\deep_Stuffs\git_cloned\PollingApplication\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\models.py", line 163, in create_superuser return self._create_user(username, email, password, **extra_fields) File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\models.py", line 146, in _create_user user.save(using=self._db) File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save super().save(*args, **kwargs) File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, … -
Is there a query set to compare id of two different model and if id matched i wanna auto fill the html form?
I want to auto-fill my one form when I enter Id then data related to that id is auto fill-in HTML form like Name, Address, Gender, Email, Images, etc. I am not seeing any errors but the code doesn't work as expected Both salary payment model and staff registration model are of Different apps When I register a staff his/her id and another detail are saved in the database with their unique Id and when I give staff his/her salary I want to auto-fill the HTML form when I enter the id of the particular staff. If both staff registration id is equal to the id we have typed in salary payment form matched then data related to that id is autofill in HTML form where user can see #This is my salary payment model:- class SalaryPayment(models.Model): Staff_id = models.UUIDField(primary_key=True) Staff_Image = models.ImageField(null = True,blank = True) Staff_Name = models.CharField(max_length=256) Staff_Address = models.CharField(max_length=256) Staff_Phone = models.CharField(max_length=15) Staff_Profession = models.CharField(max_length=256) Gender = models.CharField(max_length=15) Citizen_Ship_No = models.CharField(max_length=150) Staff_Basic_Salary = models.DecimalField(max_digits=10,decimal_places=2) Staff_Extra_Income = models.DecimalField(max_digits=10,decimal_places=2) Total = models.DecimalField(max_digits=20,decimal_places=2,default=0.00) slug = models.SlugField(unique=True,allow_unicode=True) #This is my Staff registration model:- class StaffRegistration(models.Model): Staff_id = models.UUIDField(primary_key=True,default=uuid.uuid4) Staff_Image = models.ImageField(blank = True,null = True) Name = models.CharField(max_length=250,null=False) Address = … -
Google recaptcha v2 not getting a response django
when I go to this site: https://www.google.com/recaptcha/api/siteverify, it show this on my screen as shown below, is there something wrong with my code? Do I need I need to change my 'g-recaptcha-response'? I already added both the site key and the secret key in my settings.py "success": false, "error-codes": [ "missing-input-secret" ] } views.py def login_user(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) ''' Begin reCAPTCHA validation ''' recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': 'aaaaaaaaaaaaaaaaaaaaaaa', 'response': recaptcha_response } data = urllib.parse.urlencode(values).encode() req = urllib.request.Request(url, data=data) response = urllib.request.urlopen(req) result = json.loads(response.read().decode()) ''' End reCAPTCHA validation ''' if user is not None and user.is_admin: request.session['userid'] = user.pk # retrieve the user id login(request, user) messages.success(request, "You have login to the admin page") return redirect('home') if user is not None and user.is_logistic: # # authenticated if user is a logistic request.session['userid'] = user.pk # retrieve the user id login(request, user) messages.success(request, "You have login to the logistic page") return redirect('logistic') # redirect the user to the logistic page if user is not None and user.is_customer: # authenticated if user is a customer service request.session['userid'] = user.pk # retrieve the user … -
Images are not loading from aws S3
I am doing a Django project. I have hosted my static files on AWS S3.It has been successfully uploaded to it. But,the images are not loading when I run the server. When I inspect the image field it shows: https://django-ecommerce-files.s3.amazonaws.com/images/logo.png%22%20id=%22image%22%20style=%22width:%2040px;%20height:40px%22%3E When I double clicked it. It shows this error: <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>07PX6KHYASHT3008</RequestId> <HostId>pJCxChq1JHlw/GL0Zy/W+PvX1TevOf/C60Huyidi8+0GMAs8geYlXSrEgo6m9vllL0PouTn6NAA= </HostId> </Error> -
How to tokenize/encrypt fields in django?
In the following screenshot the actual password look like Password123 but when I run user = User.objects.create(...) user.set_password('Password123') user.save() #then in login I have to run from django.contrib.auth import authenticate user = authenticate(username=username, password=password) user.... However, Django will automatically set it like this handle the necroption or the tokenization whatever you name this, and the parsing in authenticate function. The question: I want to do the same for an integer field in order to prevent even the admin from seeing that field so it will be a secret fied only the user can see. -
Django Model Data dynamic with column name and value
During django create new records in dynamic way got error, ID is expection number but got 'OrderNo= "Order No", OrderSuffix= "Order Suffix", Reference= "Reference", ItemCode= "Item Code", QtyOrdered= "Qty Ordered", QtyShipped= "Qty Shipped", Warehouse= "Warehouse", DispatchDate= "Dispatch Date", TrackingNo= "Tracking No", CarrierCode= "Carrier Code"' But if i put this string like data = quatius_shipment(OrderNo= "Order No", OrderSuffix= "Order Suffix", Reference= "Reference", ItemCode= "Item Code", QtyOrdered= "Qty Ordered", QtyShipped= "Qty Shipped", Warehouse= "Warehouse", DispatchDate= "Dispatch Date", TrackingNo= "Tracking No", CarrierCode= "Carrier Code") for row in table: ind = 0 rowdata = '' for col in config['header_columns']: rowdata += col['title'] + '= "' + row[ind] + '"' + ', ' ind = ind + 1 rowdata = rowdata[:-2] #return HttpResponse(rowdata) data = quatius_shipment(rowdata) data.save(using="integration") That means created string variable if i put directly for make it dynamic its showing "ID" expected a number but the string if i put its totally working fine. May anyone help me.Thanks in Advance. -
Django Template Inheritance and For Loop
I have two HTML file app/blog.html <h1>TEST</h1> {% for blog in blogs %} <h1>{{ blog.title }}</h1> <p>{{ blog.author }}</p> {% endfor %} app2/mainpage.html {% extends 'base.html' %} {% load static %} {% block content %} {% include 'app/blog.html' %} //it only shows TEST with heading 1, but each blog inside for loop isnt showing {% endblock content %} I tried to create seperate url for blog.html, and it works fine (each blog inside for loop is rendered) Is it possible to show each item inside for loop using include? How can i do that? Thanks. -
ModelForm not saving to the database
I currently have a ModelForm in a Django-Python web app that allows users to edit settings for financial documents. The form currently does not save into the database for some reason. I think that this is due to the validity of the form/model. Is it because some BooleanFields are True/False or is it something to do with the way the form is imported. I tried to check if the fact that I am using 2 forms for the same model is causing a problem but I can't seem to see an error here. Please see the below code: Views.py: def viewSettings(request, settings_pk): setting = get_object_or_404(SettingsClass, pk=settings_pk) if request.method == 'GET': form = SettingUpdateForm(instance=setting) return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form}) else: form = SettingUpdateForm(request.POST, instance=setting) if form.is_valid(): form.save() return redirect('settingsHome') return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form}) Forms.py: class SettingsForm(ModelForm): class Meta: model = SettingsClass fields = ('Complex','Trial_balance_Year_to_date' , 'Trial_balance_Monthly' , 'Income_Statement_Year_to_date' , 'Income_Statement_Monthly' , 'Age_Analysis' , 'Balance_Sheet' , 'Repair_and_Maintenance_General_Ledger' , 'Major_capital_Items_General_Ledger') class SettingUpdateForm(ModelForm): class Meta: model = SettingsClass fields = '__all__' Models.py: class SettingsClass(models.Model): Complex = models.CharField(choices=complex_list , max_length = 22 ,default='1' , unique=True) #Trial Balance Year To Date Trial_balance_Year_to_date= models.BooleanField(default = False) tbytd_Include_opening_balances=models.BooleanField(default = False) tbytd_Only_use_main_accounts=models.BooleanField(default = False) tbytd_Print_null_values=models.BooleanField(default = … -
SQL database connections over 800,000?
Yes, I know. Seemingly impossible for a 2GB RAM server, right? show status like 'Conn%'; Returns: (constantly climbing) Connections: 809662 But I am using a Django web app, which normally closes threads after the page is loaded. Not using any manual queries. Plus, I have my max_connections set to 300, so how could it even be this high? Am I misunderstanding something? How do I see current connection count, if not this? Users hit an API endpoint through a refresh widget once every 45 seconds, but the endpoint is cached for 40 seconds... so most of those requests should not be doing DB queries. I have confirmed the cache is working too, which is done through memcached. -
Importing Django seriliazer fields into another seriliazer feilds
I am currently working on a website for my students where it will help them to book some items on the classroom. I am already done with the booking logic and form so no two students are allowed to book the same item at the same time. I would like to create a table for them where it shows the item name and the status of the item based on the current time, and the current owner of the item at the momment. The thing is I have three models. The first one is Details where it have all information about the items, the other model is Item which simply list the Item name, and last is the Booking model which I use for the booking form and logic, this model will create a list of all bookings made by the students. class Details(models.Model): item_name = models.CharField(max_length=50, editable=False) item_id= models.IntegerField(editable=False) Publish_date = models.DateField() auther = models.CharField(max_length=20) def __str__(self): return self.item_name class Items(models.Model): ITEMS_CATEGORIES=( ('item-1', 'item-1'), ('item-2', 'item-2'), ('item-3', 'item-3'), ('item-4', 'item-4'), ('item-5', 'item-5'), ) category = models.CharField(max_length=5, choices=ITEM_CATEGORIES) def __str__(self): return self.category class Booking(models.Model): user = models.CharField(max_length=50, editable=False) note = models.CharField(max_length=300, default='SOMESTRING') item = models.ForeignKey(Subsystem, on_delete=models.CASCADE) check_in = models.DateTimeField() check_out … -
Problem including an external JQuery into Django template
The template below has no problems if I run it inside the same html template. But if I put the JQuery code in a country_dropdown.js external file inside the static folder, and I include it like that: <script src="{% static 'js/countries.js' %}"></script> then the following: url: "{% url 'get-province' %}", will not work. It seems that the {% tags are not recognized inside external js files, even if they should. In fact the requested is rendered this way: Request URL: http://127.0.0.1:8000/countries/%7B%25%20url%20'get-province'%20%25%7D Obviously the %7B means { and the %25 means %. Therefore template tags are not properly recognized outside the template. But, since I will use the same functionality and the same drop-down list in several places, it would be a very good practice to put the JQuery in an external file and include it when I need it instead of duplicating it in each template where it is needed. How could I include the external JQuery without problems? I have included the complete template here. {% extends 'base.html' %} {% load i18n %} {% load static %} {% block content %} <form class="" action="" method="post"> {% csrf_token %} {% for error in errors %} <div class="alert alert-danger mb-4" role="alert"> … -
Django override save method problem that create two different ids for the meeting
I had override a save method for my Meeting model which will generate a random id for the meeting_ID whenever user create a meeting. The save method itself is successful but the problem is that somehow the override save() method generate two random ids instead of just one for the created meeting. Meaning that when I click on Save button, it will create two identical meetings with different meeting_ID. I don't know what is the issue as I'm a beginner for Django. Thanks in advance. Model.py class Meeting(models.Model): MEETING_STATUS = ( ('Coming Soon', 'Coming Soon'), ('Live', 'Live'), ('Closed', 'Closed') ) meeting_ID = models.CharField(primary_key=True, max_length=6, validators=[RegexValidator(r'^\d{6,6}$')], null=True) meeting_title = models.CharField(max_length=400, null=True) meeting_date = models.DateField() meeting_time = models.TimeField() meeting_desc = models.CharField(max_length=500, null=True) meeting_status = models.CharField(max_length=200, null=True, choices=MEETING_STATUS) date_created = models.DateTimeField(default=timezone.now, null=True) def __str__(self): return self.meeting_ID def save(self, *args, **kwargs): meetingID = random.randint(100000,999999) if not Meeting.objects.filter(meeting_ID=str(meetingID)).exists(): self.meeting_ID = str(meetingID) print(self.meeting_ID) super(Meeting, self).save(*args,**kwargs) class Resolutions_Meeting(models.Model): reso_ID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) resolution = models.CharField(max_length=400) meeting_id = models.ForeignKey(Meeting, related_name="has_meetings", on_delete=CASCADE, null=False) def __str__(self): return str(self.meeting_id) Views.py class MeetingsCreate(CreateView): model = Meeting template_name = 'meetings/create_meetings.html' # fields = ['meeting_ID', 'meeting_title', 'meeting_date', 'meeting_time', 'meeting_desc', 'meeting_status'] form_class = MeetingForm success_url = None def get_context_data(self, **kwargs): data = super(MeetingsCreate, self).get_context_data(**kwargs) … -
Add date from external API to view response - Django
I'm trying to add some data from an external API to a view response. My view already send data from my database, and I want to add some data from an external API call in the view. Models: class Currency(models.Model): """Store information about a currency asset.""" id = models.IntegerField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class Price(models.Model): """Store price about a currency asset.""" currency = models.ForeignKey(Currency, related_name="price", on_delete=models.CASCADE) price = models.FloatField(blank=True, null=True) View: class CurrencyViewSet(viewsets.ModelViewSet): serializer_class = serializers.CurrencySerializer queryset = models.Currency.objects.all() def get_queryset(self): currencies = self.request.user.currencies_set.all() ids = [currency.id for currency in currencies] price = fetch_currency_price(ids) # fetch from external api for currency in currencies: currency.price.set(Price(currency_id=currency.id, price=price.get('id')) return currencies Which doesn't work. I got tons of different errors and I can't figure it out. -
Uncaught TypeError: $(...).modal is not a function with webpack using bootstrap in django application
Scoured stackoverflow and played around with webpack plugin config, but still getting Uncaught TypeError: $(...).modal is not a function even when importing Bootstrap's .modal function through webpack. The imports I have tried in the file to use Bootstrap's .modal function are import 'bootstrap' and import 'bootstrap/js/dist/modal'. These imports were directly in the file that they were being used in. Every other import works except for bootstrap it seems. webpack.config.js module.exports = { mode: 'development', entry: { index: './objectivedeck/static/js/index.js', unauthed: './objectivedeck/static/js/unauthed.js' }, output: { filename: 'main.js', filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist'), sourceMapFilename: "[name].js.map" }, devtool: "source-map", plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', Popper: ['popper.js', 'default'], Modal: 'exports-loader?Modal!bootstrap/js/dist/modal', }), ] } I have installed exports-loader and everything is compiling and the js is being bundled to the output without any errors. Since I was having trouble with the source map files I had stackoverflow-ed a solution so you'll see I have added a seperate output that may not usually be there (sourceMapFilename: "[name].js.map") but it resolved the source map issue. Sadly it didn't solve the issue with .modal. One thing I have maybe brought it down to was that somehow bootstrap isn't seeing jquery and it's not creating … -
Why do I need to specify HTML file in render()
Why do I need to give html file name in render() - I have already set url in my project file in urls.py in django urls.py url('view-books',views.viewBooks) views.py def viewBooks(request): books=models.Book.objects.all() res=render(request,'BRMapp/view_book.html',{'books':books}) Why can I not give in render view-books? -
Django Queryset - Get counts by model.choices
I have below model, which has all the details about customer Leads. Customer wants to see his Leads followup statuses. class FollowUp(models.Model): CALL_CHOICES = [("0", "Call Unanswered"), ("1", "Call Later"), ("2", "Visit Scheduled"), ("3", "Not Visited"), ("4", "Not reachable"), ("5", "Wrong Number"), ("6", "Not Interested"), ("7", "Deal Closed")] status = models.CharField(_("Call Status"), max_length = 20, choices = CALL_CHOICES, default = '1' ) next_action_on = DateTimeField(_("Next Action"), auto_now_add=False, null=True, blank=True) reminder = models.BooleanField(_("reminder"), default=False) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Lead(models.Model): followups = models.ManyToManyField(FollowUp, verbose_name=_("Follow up"), blank=True) ... How can I get Lead counts of each status choice. such as { 'Call Unanswered': 12 #Leads, 'Call Later': 10 # Leads 'Visit Scheduled': 20, #Leads, ... } -
I am not able to uplaod image in django ekeditor
I want to text editor just like stack over flow have for the images i can edit the image properly as well as text i watch some videos they show that they can do this by configuring the django setting django project url i did the same now i was able to paste image in the text fiels editor but it was only for the superuser for the user in frontent they can upload it shows when i search on google it says this error because ckeditor is develop with default login required for the admin you can read the same documentation here read here so when i fololow the things it say says gives me bigger error now nobody can upload images it says error 404 -
How to save env variable in osX in django
this might occur as a naive question. I am using cookie cutter django template and have to set env variables every time restarts the project. I am doing the following every time I start working on the project export env_var_for_project=some_value What I need to do in order to have these variables stored so that I don't have to export every time I open up my project -
How to know when chained django lifecycle hooks/signals are finished running?
I have an Animal model and a Herd model that looks like this: from django_lifecycle.hooks import AFTER_CREATE class Animal(models.Model): parent = OneToOneField("self", related_name="child") age = IntegerField() class Herd(models.Model): animal = OneToOneField(Animal) total_age = IntegerField() @hook(AFTER_CREATE) def create_animal_child(self): if self.animal.child.exists(): Herd.objects.create(parent=self, animal=self.animal.child) def save_total_age(self): total_age = self.animal.age position = self.animal while position.child.exists(): total_age += position.child.age position = position.child The idea being that you create your Animals. Then you create your Herd for the topmost animal you want. The Herd's AFTER_CREATEwill then create a "chain" of all the Herd objects for the Animal's children, the children's children, and so on. E.g. a1 = Animal.objects.create(age=10) a2 = Animal.objects.create(parent=a1, age=7) a3 = Animal.objects.create(parent=a2, age=3) h1 = Herd.objects.create(animal=a1) # Two Herd objects with an "animal" field pointing to a2 and a3 respectively are automatically created h1.save_total_age() # h1.total_age = 20 # 10 + 7 + 3 Which is all fine. My problem is for my front-end, how can I tell when all the relevant Animal AFTER_CREATE hooks have finished running so I know to call my calculate_total_age method? So say I have the following REST API endpoints: example.com/api/animals/<pk> example.com/api/herds/<pk> example.com/api/herds/<pk>/save_total_age If I do a POST to example.com/api/herds/<pk> to create a Herd, I call save_total_age() as … -
ModuleNotFoundError: No module named 'setuptools_rust' when deploying Django app to AWS Elastic Beanstalk
I have a Django web app that I wish to deploy to elastic beanstalk. I have cryptography package inside requirements.xml. When I do eb deploy it gives ModuleNotFoundError: No module named 'setuptools_rust' error. I created requirements.txt with pip freeze command. What's wrong with setuptools_rust? -
Problem installing mysqlclient for Django project (macOS)
When connecting my Django project to a database hosted on a remote VM, when I run python3 manage.py run server I get the error django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? when I try python3 -m pip install mysqlclient to resolve the dependency, I get the error ERROR: Could not find a version that satisfies the requirement mysqlclient (from versions: 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.3.8, 1.3.9, 1.3.10, 1.3.11rc1, 1.3.11, 1.3.12, 1.3.13, 1.3.14, 1.4.0rc1, 1.4.0rc2, 1.4.0rc3, 1.4.0, 1.4.1, 1.4.2, 1.4.2.post1, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 2.0.0, 2.0.1, 2.0.2, 2.0.3) ERROR: No matching distribution found for mysqlclient I'd like to understand what is causing these issues and how to resolve it. Thanks in advance! -
Django url file is calling the wrong function
I'm trying to call a function to write a file, but my Django url.py seems to be calling the markdown function. When you press the submit button on the form in the HTML, you get an error that throws at the line "if query["q"] in entries:". HTML <h1>New Page</h1> <form action="{% url 'newPage'}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" id="title" name="t" placeholder="Title"> </div> <div class="form-group"> <label for="content">Content</label> <textarea class="form-control" id="content" rows="10" name="c" placeholder="Markdown content"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> views.py def markdown(request, entry): pathOfFile = "entries/" + entry + ".md" entries = util.list_entries() query = request.POST if request.method == "POST": if query["q"] in entries: return render(request, "encyclopedia/entry.html", { "html_markdown": markdown2.markdown_path("entries/"+query["q"]+".md") }) else: searchResults = [] if query["q"] in entries: for i in entries: if query["q"] in i: searchResults.append(i) return render(request, "encyclopedia/search.html", { "searchResults": searchResults }) else: return render(request, "encyclopedia/error.html") else: if (entry in entries): return render(request, "encyclopedia/entry.html", { "html_markdown": markdown2.markdown_path(pathOfFile) }) else: return render(request, "encyclopedia/error.html") def newPage(request): if request.method == "POST": query = request.POST title = query["t"] content = query["c"] util.save_entry(title, content) else: return render(request, "encyclopedia/newPage.html") urls.py urlpatterns = [ path("", views.index, name="index"), path("error", views.error, name="error"), path("newPage", views.newPage, name="newPage"), path("<str:entry>", views.markdown, name="entry") -
ModuleError: No module named <appname>.url
I have been trying to make a django project, but I can't make an app. python3 manage.py startapp app In settings.py: INSTALLED_APPS = [ 'app', <All other django.things> ] In urls.py: from django.urls import path, include urlpatterns = [ path('app/', include('app.urls')), path('admin/', admin.site.urls), ] Note: These are exerpts But I still get this error: ModuleNotFoundError: No module named 'app.urls' -
Detect When Entire Field is Empty / Has No Inputs - Django - Python
I need a way to detect when all a field in my models has no entries in it at all. I need it to see every submitted entry and detect when a field has been left blank every single time. I know this is possible using {% empty %} in a forloop but that works for the whole forloop. Do I so this is my views.py? views.py def repo1(request): context = {} context['Add_Repo'] = Add_Repo.objects.filter(user=request.user) context['Data_Repo1'] = Data_Repo1.objects.filter(user=request.user) context['Field_Repo1'] = Field_Repo1.objects.filter(user=request.user) return render(request, 'sheets/list_repo/repo1.html', context) Data_Repo1 contains the data that I need to detect if a field is left completely empty and what field that is. HTML {% for post in Data_Repo1 %} <tr> <td><div><a href="{% url 'update_extinguisher' pk=post.pk %}" style="color: black;">{% if post.date1 %}{{ post.date1 }}{%else%}<span style="color: white;">None</span>{%endif%}</a></div></td> <td><div><a href="{% url 'update_extinguisher' pk=post.pk %}" style="color: black;">{% if post.date2 %}{{ post.date2 }}{%else%}<span style="color: white;">None</span>{%endif%}</a></div></td> <td><div><a href="{% url 'update_extinguisher' pk=post.pk %}" style="color: black;">{% if post.date3 %}{{ post.date3 }}{%else%}<span style="color: white;">None</span>{%endif%}</a></div></td> </tr> <tr> {% endfor %} I'm really stuck and just don't know if it's possible at this point. Thanks!