Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am getting broken image in a html(cart) page
I am creating an add-to-cart function for my website. I am getting broken images in my cart.html page. So, In cart.html: {% for product_id, item in data.items %} <div class="col-md-12 col-lg-8"> <div class="items"> <div class="product"> <div class="row"> <div class="col-md-3"> <img class="img-fluid mx-auto d-block image" src="{{item.image}}" > <!-- #1 --> </div> <div class="col-md-8"> <div class="info"> <div class="row"> <div class="col-md-5 product-name"> <div class="product-name"> <a href="#">{{item.title}}</a> <div class="product-info"> <div>Display: <span class="value">5 inch</span></div> <div>RAM: <span class="value">4GB</span></div> <div>Memory: <span class="value">32GB</span></div> </div> </div> </div> <div class="col-md-4 quantity"> <label for="quantity">Quantity:</label> <input id="quantity" type="number" value ="1" class="form-control quantity-input"> </div> <div class="col-md-3 price"> <span>{{item.price}}</span> </div> </div> </div> </div> </div> </div> </div> </div> You can see in the #1 that I add the image there. I also created view for add-to-cart function So, in views.py: def add_to_cart(request): cart_product={} cart_product[str(request.GET['id'])]={ 'title': request.GET['title'], 'qty': request.GET['qty'], 'price': request.GET['price'], 'image': request.GET['image'], 'pid': request.GET['pid'], } if 'cart_data_obj' in request.session: if str(request.GET['id']) in request.session['cart_data_obj']: cart_data= request.session['cart_data_obj'] cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty']) cart_data.update(cart_data) request.session['cart_data_obj']=cart_data else: cart_data=request.session['cart_data_obj'] cart_data.update(cart_product) request.session['cart_data_obj']=cart_data request.session['total_cart_items'] = len(cart_data) else: request.session['cart_data_obj']=cart_product request.session['total_cart_items'] = len(cart_product) return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items']}) In the function.js: $("#add-to-cart-btn").on("click",function(){ let quantity=$("#product-quantity").val() let product_title=$(".product-title").val() let product_id=$(".product-id").val() let product_price = $("#current-product-price").text() let product_image = $(".product-image").val() let product_pid=$(".product-pid").val() let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("PId:", product_pid); console.log("Image:", product_image); console.log("Title:", product_title); … -
Django 5 postgres superuser login fail
I created a Django project SQLite. I decided to move from SQLite to PostgreSQL. All migrations worked. I created the superuser successfully but when I try logging in the admin it says that the user can't be found. this is the users model from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): """ Class for creating custom users. There are 3 user types in this class """ USER_TYPE_CHOICES = ( ('manager', 'Manager'), ('supervisor', 'Supervisor'), ('employee', 'Employee'), ) user_type = models.CharField(max_length=20, choices=USER_TYPE_CHOICES) is_active = models.BooleanField(default=False) name = models.CharField(max_length=255) email = models.EmailField(unique=True) national_id = models.CharField(max_length=20, unique=True) def __str__(self): return self.email # Provide a unique username or remove the unique constraint from email def save(self, *args, **kwargs): if not self.username: self.username = self.name # Use email as username or provide a unique username super().save(*args, **kwargs) I tried logging in the admin. It says the user is not found. I used both email and username to be sure but the user still can't be found. This is pip freeze: pip freeze asgiref==3.7.2 attrs==23.1.0 bcrypt==4.1.2 Django==5.0 django-cors-headers==4.3.1 django-filter==23.5 djangorestframework==3.14.0 djangorestframework-simplejwt==5.3.1 drf-spectacular==0.27.0 Faker==21.0.0 inflection==0.5.1 jsonschema==4.20.0 jsonschema-specifications==2023.11.2 Markdown==3.5.1 mysqlclient==2.2.3 psycopg2==2.9.9 PyJWT==2.8.0 python-dateutil==2.8.2 pytz==2023.3.post1 PyYAML==6.0.1 referencing==0.32.0 rpds-py==0.15.2 six==1.16.0 sqlparse==0.4.4 typing_extensions==4.9.0 uritemplate==4.1.1 -
Export file automatic download not working in Django
I have trouble when exporting excel file through export button it does not appear download automatically, but when I inspect element then selecting network if I clicked export status it will download, but for me it will hassle to inspect element instead just click one button. I used Chrome I already tried set to automatic download but the result will the same, Is this the issue for the new version of the web browser or in my code? This is my code @csrf_exempt def export_status(request): with connection.cursor() as cursor: cursor.execute(""" SELECT tev_incoming.id,tev_outgoing.dv_no AS dv_no, tev_incoming.code, tev_incoming.account_no, tev_incoming.id_no, tev_incoming.first_name, tev_incoming.middle_name, tev_incoming.last_name, tev_incoming.date_travel, tev_incoming.division, tev_incoming.section, tev_incoming.status_id, au.first_name AS incoming_by,rb.first_name AS reviewed_by, tev_incoming.original_amount, tev_incoming.final_amount, tev_incoming.incoming_in AS date_actual, tev_incoming.updated_at AS date_entry, tev_incoming.incoming_out AS date_reviewed_forwarded, tev_bridge.purpose AS purposes FROM tev_incoming INNER JOIN ( SELECT MAX(id) AS max_id FROM tev_incoming GROUP BY code ) AS latest_ids ON tev_incoming.id = latest_ids.max_id LEFT JOIN tev_bridge ON tev_incoming.id = tev_bridge.tev_incoming_id LEFT JOIN tev_outgoing ON tev_bridge.tev_outgoing_id = tev_outgoing.id LEFT JOIN auth_user AS au ON au.id = tev_incoming.user_id LEFT JOIN auth_user AS rb ON rb.id = tev_incoming.reviewed_by ORDER BY tev_incoming.id DESC; """) rows = cursor.fetchall() response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename={date}-TRIS-REPORT.xlsx'.format( date=datetime.now().strftime('%Y-%m-%d'), ) workbook = Workbook() worksheet = workbook.active worksheet.title … -
Django hosting in cpanel with out using Setup Python App
I want to host my Django project in cPanel with out using Setup Python App. How can i do that? Please provide step by step solution from beginning. I search for the solution in google, but i can't get the answer. Please help me. -
Django admin : How to show a model as inline inside another model, which is indirectly related
I have models named user, authtoken and userdevice. class User(LifecycleModelMixin, AbstractUser): email = models.EmailField(unique=True) slug = models.SlugField(max_length=100, unique=True, blank=False, null=True) class AuthToken(models.Model): objects = AuthTokenManager() digest = models.CharField( max_length=CONSTANTS.DIGEST_LENGTH, primary_key=True) token_key = models.CharField( max_length=CONSTANTS.TOKEN_KEY_LENGTH, db_index=True) user = models.ForeignKey(User, null=False, blank=False, related_name='auth_token_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) expiry = models.DateTimeField(null=True, blank=True) class UserDevice(models.Model): token = models.OneToOneField(AuthToken, on_delete=models.CASCADE, related_name="auth_token") device_type = models.CharField(max_length=100, choices=DevicesChoices.choices) access_type = models.CharField(max_length=100, choices=AccessChoices.choices) device_brand = models.CharField(max_length=100, null=True, blank=True) I need to show the userdevice inside the user detail page in admin panel as inline. Django Error admin.E202 'userdevice' has no ForeignKey to 'accounts.user' Getting this error. Any help will be much appreciated. -
MySQL/Django/Docker -> 1045, "1045 (28000): Access denied for user 'X'@'xx.xxx.xx.xx' (using password: YES)", '28000'
I have mariadb/mysql and django running as separate docker containers (both have separate docker-compose.yml files as well). When I try to build my django docker container using docker-compose build(I have a Dockerfile defined for this with makemigrations and migrate commands in it) my container builds fine and correctly and python manage.py makemigrations and python manage.py migrate work fine as well. However when I do docker exec -ti <django-container-name> bash and try to run python manage.py makemigrations and python manage.py migrate, it doesn't work. I get a 1045, "1045 (28000): Access denied for user '<user>'@'<host>' (using password: YES)", '28000'error. Similarly, when I try to do mysql -h <hostname> -P <port> -u <username> -p I get a bash error saying that mysql doesn't exist (I also get this same error when i do just mysql). Accessing MariaDB: When I do docker exec -ti <mariadb-container-name> bash and run the mysql command, I am able to see the migrations from the initial django build but nothing else after that. Where am I going wrong that django can build and do makemigrations/migrate fine but won't run these commands inside the docker container once it is up and running? I should clarify that mariadb/mysql and django … -
React Router version issue [duplicate]
I just had a quick question about a React project I'm working on. I'm trying to get React Router to route to both a login page and, upon successfully doing that, have it re-route to my app's homepage. However, I'm using version 6, and I keep getting the following error when I try to run it: "[PrivateRoute] is not a component. All component children of must be a or <React.Fragment>" Any insight into how I can reformat my code? Thanks!! import React from 'react'; import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom'; import Login from './Login'; import Spreadsheetester from './Spreadsheet'; const PrivateRoute = ({ element: Element, ...rest}) => ( <Route {...rest} element={ localStorage.getItem('token') ? ( <Element /> ) : ( <Navigate to="/login" replace /> ) } /> ); const App = () => { return ( <Router> <Routes> <Route exact path="/login" element={<Login />} /> <PrivateRoute exact path="/" element={<Spreadsheet />} /> </Routes> </Router> ); }; export default App; -
Wagtail and Elasticsearch , Lookup "icontains"" not recognised
I'm trying to run a search with Wagtail (5.2) and Elastic (7) When I make a search for Users wagtail_admin/users/?q=ffff I got such error FilterFieldError Cannot filter search results with field "email". Please add index.FilterField('email') to User.search_fields Then I add extra field to search fields in the code class User: search_fields = [ index.SearchField("name", partial_match=True), index.FilterField("email", partial_match=True), ] But just got another error FilterError /wagtail_admin/users/ Could not apply filter on search results: "email__icontains = ffff". Lookup "icontains"" not recognised. How it can be fixed? -
axios response.data is empty when django returns a queryset with a single element
I am using axios to get some data from my backend API made with django. Something very very wired is happening and I have been debugging this for hours. This is the axios function that gets the data: function useGetProducts(category: string, subcategory: string, code:string){ const [products, setProducts] = useState<Product[]>([]); useEffect(() => { axios.get(getQueryUrl(category, subcategory, code)) .then(response => { console.log(response) setProducts(response.data); }) .catch(error => { console.error(error); }); },[]); return products; } And here is my ProductView in django class ProductView(viewsets.ModelViewSet): serializer_class = ProductSerializer def get_queryset(self): queryset = Product.objects.all() cat = self.request.query_params.get('category', None) subcat = self.request.query_params.get('subcategory', None) code = self.request.query_params.get('code', None) if cat and subcat and code: # Sanitize the name parameter using Django's ORM queryset = queryset.filter(code__exact=code) elif cat and subcat: queryset = queryset.filter(category__exact=cat, sub_category__exact=subcat) elif cat: queryset = queryset.filter(category__exact=cat) print(queryset) return queryset Now the thing is when the queryset contains only one element the response.data is an empty array but when the queryset contains more than one element the response.data contains the right amount of elements. The method getQueryUrl works correctly. I tried to limit the output of other querysets that supposed to contain more than 1 element to 1 and same thing, empty array on the frontend side. ChatGPT … -
Django linebreaks disallow CSS Style
I have a problem in my new Django project. In fact, I've created a Model named "Tutorial" which has a Description being a TextField(). So when I call it in my HTML file from my View it works correctly for all except for this one because I need to add linebreaks if I want to keep all the body of my description. And without these linebreaks my CSS works correctly but the text goes through the content area and with linebreaks I show all the text but the CSS style is disallowed, please help me.Linebreaks code (Don't take care about striptags). Here it's without the linebreaksAnd here with linebreaks it's horrible lol Need help please I hope you can help me cause I didn't find anything anywhere. -
Cannot get nested serializers to show related data using Django REST framework
For some reason my nested serializers are not displaying related data. I've searched online for an answer but cannot find any answers that fixes this issue. The demo apps I make using nested serializers work as expected, but on my main app the nested serializers do not display related data. Below is my relevant code. ##models ... class Location(models.Model): user = models.ForeignKey(User, null=False, on_delete=models.CASCADE) name = models.CharField("Full name", max_length=100,) geolocation = models.PointField() address1 = models.CharField("Address line 1", max_length=1024,) address2 = models.CharField("Address line 2", null=True, max_length=1024,) city = models.CharField("City", max_length=50,) STATES = [ ("AL", "Alabama"), ("AK", "Alaska"), ("AZ", "Arizona"), ("AR", "Arkansas"), ("CA", "California"), ("CO", "Colorado"), ("CT", "Connecticut"), ("DE", "Delaware"), ("FL", "Florida"), ("GA", "Georgia"), ("HI", "Hawaii"), ("ID", "Idaho"), ("IL", "Illinois"), ("IN", "Indiana"), ("IA", "Iowa"), ("KS", "Kansas"), ("KY", "Kentucky"), ("LA", "Louisiana"), ("ME", "Maine"), ("MD", "Maryland"), ("MA", "Massachusetts"), ("MI", "Michigan"), ("MN", "Minnesota"), ("MS", "Mississippi"), ("MO", "Missouri"), ("MT", "Montana"), ("NE", "Nebraska"), ("NV", "Nevada"), ("NH", "New Hampshire"), ("NJ", "New Jersey"), ("NM", "New Mexico"), ("NY", "New York"), ("NC", "North Carolina"), ("ND", "North Dakota"), ("OH", "Ohio"), ("OK", "Oklahoma"), ("OR", "Oregon"), ("PA", "Pennsylvania"), ("RI", "Rhode Island"), ("SC", "South Carolina"), ("SD", "South Dakota"), ("TN", "Tennessee"), ("TX", "Texas"), ("UT", "Utah"), ("VT", "Vermont"), ("VA", "Virginia"), ("WA", "Washington"), ("WV", "West Virginia"), ("WI", "Wisconsin"), … -
Django Related Object Reference in Template
Unable to display related object reference set via foreign key relationship in HTML template. Here's the code so far. models.py: class MprVw(models.Model): payloadid = models.TextField(db_column='payLoadID', blank=True, null=True) file = models.TextField(db_column='File', primary_key=True) class Meta: managed = False db_table = 'MPR_VW' class MprWi(models.Model): id = models.TextField(db_column='id', primary_key=True) payloadid = models.TextField(db_column='payLoadID', blank=True, null=True) file = models.ForeignKey(MprVw, on_delete=models.DO_NOTHING, db_column='File') class Meta: managed = False db_table = 'MPR_WI' views.py: def MPR(request): myDls = request.GET.get("dls") myMPR = MprVw.objects.filter(dls=myDls) myMprWi = MprWi.objects.all().values() context = { 'myMPR': myMPR, 'myMprWi': myMprWi, 'myDls': myDls, } MPR = loader.get_template('MPR.html') return HttpResponse(MPR.render(context, request)) HTML: {% for rowmyMPR in myMPR.mprwi_set.all %} <tr> <td>{{ rowmyMPR.file }} {{ rowmyMPR.id }} </td> </tr> {% endfor %} I am expecting to display row data from myMprWi that are the child records of the myMPR parent file. There is currently nothing displaying. -
What is messing with the logging in AsyncWebsocketConsumer?
I have a Django project that's using Channels for websocket communication and I've stumbled upon what I think might be a bug, but I'm not certain so I'm hoping someone that understands this better than I do can help explain what's happening here: Test error message: AssertionError: "INFO:websocket.camera_consumer:Doesn't work" not found in ['INFO:websocket.camera_consumer:Works'] Test that's failing: class TestCameraConsumerTests(TransactionTestCase): async def test_fails(self): communicator = WebsocketCommunicator(TestConsumer.as_asgi(), '/ws/device') with self.assertLogs(f'websocket.camera_consumer', level=logging.INFO) as logs: await communicator.connect(timeout=10) await communicator.disconnect() self.assertIn(f"INFO:websocket.camera_consumer:Doesn't work", logs.output) websocket.camera_consumer.py: import logging from channels.generic.websocket import AsyncWebsocketConsumer def sync_function(): pass class TestConsumer(AsyncWebsocketConsumer): async def connect(self): await super().connect() logger = logging.getLogger(__name__) logger.info("Works") await sync_to_async(sync_function)() logger.info("Doesn't work") What I've learned so far: Moving the getLogger call outside the connect function doesn't fix it Moving the super call below the sync_to_async call does fix it Removing the sync_to_async function (and making sync_function async) also fixes it Somewhere along the way in the sync_to_async function call, the logger handler object that the assertLogs injects gets removed so the first log message gets routed to the test, but the second log message does not I've attempted to step-though the sync_to_async call, however I can't figure out how to monitor the logger object while inside the async loop (I'm … -
Django language switcher is not persistent
Hello I'm struggling with my language switcher. settings.py: LANGUAGE_CODE = 'en' LANGUAGES = [ ('de','Deutsch'), ('en','English') ] urls.py: path('setlang', views.setlang, name='setlang'), index.html: <a href="{% url 'setlang' %}">{% trans "English" %}</a> views.py def setlang(request): logger.error(get_language()) if get_language() == 'de': activate('en') else: activate('de') logger.error(get_language()) return redirect('index') Output from logger.error(get_language()) -> 'de' than 'en'. It's everytime 'de'! Even if I set LANGUAGE_CODE = 'en'! I've no idea where the 'de' is coming from. The problem is maybe the reload, which is forced by the return redirect('index')? Translation in general works. Has anyone an idea how I can stick to the language which is selected and not fall back to default? -
Access to Django Session with React
I'm new to React and I wanna Access my Django sessions with React framework. In this case I have an array in my session named UserInfo that I can access with request.session['UserInfo'] in Django. I wanna know how can I get UserInfo data in React side and work with it? Literally how can we get or pass data from frontend to backend between these two? -
What is the best way to use phone number and validation code in django?
I want to bulid a backend appliaction in django, an i want to have authatication using only phone number, after the client write the phone number he will get a code via sms what is the best way to approch this ? how can i modify the login and authaticate methods in django base user model -
Django ADFS mock for unit tests
I use django_auth_adfs in my app. I need to mock it to perform view tests. The thing is that I've no idea which object should I mock. This is my one of my test used before installation of django_auth_adfs and fixture draft. class TestAPIVew: API_URL = reverse("list") @pytest.fixture def adfs(self): with patch('object_to_mock') as mock_auth: yield mock_auth def test_view_returns_correct_json(self, client, adfs): response = client.get(self.API_URL) data = response.json() assert response.status_code == HTTPStatus.OK assert data == {"key": "value"} QUESTION What should I do to omit authentication etc to make the test work as the user is logged in" -
Unable to load a Django model from a separate directory in a database script
I am having difficulty writing a python script that takes a directory of .txt files and loads them into my database that is utilized in a Django project. Based on requirements the python script needs to be located in a separate directory than the api (my django directory). Here is my project structure currently: Main-Project/ database/ text-script.py text-files/ example-file.txt django/ django/ settings.py snippets/ models.py My text-script.py file looks like this: import os import sys import django current_dir = os.path.dirname(os.path.abspath(__file__)) parent_dir = os.path.dirname(current_dir) sys.path.append(parent_dir) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django.django.settings') django.setup() from django.snippets.models import Snippet def import_articles(directory): for filename in os.listdir(directory): if filename.endwith('.txt'): with open(os.path.join(directory, filename), 'r') as file: content = file.read() Snippet.objects.create(filename=filename, content=content) if __name__ == '__main__': text_dir = os.path.join(current_dir, 'text-files') import_articles(text_dir) My installed apps looks like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'snippets.apps.SnippetsConfig', ] I get this error when I try to run the script: ModuleNotFoundError: No module named 'snippets' How do I correctly load the Snippet model from my Django project to utilize the same database used in my Django project? -
.gz archive have the content-type identified wrong?
I'm working on an API that handles uploaded images. Images can be both .jpg files and .gz archives. url = 'http://example.com/upload' file_path = 'path/to/my/file.gz' files = {'file': open(file_path, 'rb')} response = requests.post(url, files=files) How can I correctly identify if the file is a jpg or a gz archive? def post(self, request): for _, file_data in request.FILES.items(): print(file_data.content_type) if file_data.content_type == 'application/gzip': # do something elif file_data.content_type.startswith('image/'): # do something The problem with this code is that after printing, it displays 'application/octet-stream' and I don't understand why. -
I am getting MultiValueDictKeyError when I am clicking on add to cart button
I created an add-to-cart function for my website so in my product-detail.html: {% for p in products %} <div class="product-price"> <span id="current-product-price">Our Price:{{p.price}}</span> <del>M.R.P: {{p.old_price}}</del> </div> <div class="button"> <input type="hidden" value="{{p.id}}" class="product-id" name=""> <input type="hidden" value="{{p.title}}" class="product-title" name=""> <a href="#" class="btn" id="add-to-cart-btn">Add to cart</a> <a href="#" class="btn">Buy Now</a> </div> {% endfor %} In my function.js: $("#add-to-cart-btn").on("click",function(){ let quantity=$("#product-quantity").val() let product_title=$(".product-title").val() let product_id=$(".product-id").val() let product_price = $("#current-product-price").text() let product_image = $(".product-image").val() //#1 let product_pid=$(".product-pid").val() //#2 let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("PId:", product_pid); console.log("Image:", product_image); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Current Element:", this_val); $.ajax({ url: '/add-to-cart', data: { 'id': product_id, 'pid': product_pid, 'image':product_image, 'qty': quantity, 'title': product_title, 'price': product_price }, dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(res){ this_val.html("Go to Cart") console.log("Added products to cart"); $(".cart-items-count").text(response.totalcartitems) } }) }) In the above js program is anything is wrong for the value error in product_pid(#2) & product_image(#1) and in my...... views.py: def add_to_cart(request): cart_product={} cart_product[str(request.GET['id'])]={ 'title': request.GET['title'], 'qty': request.GET['qty'], 'price': request.GET['price'], 'image': request.GET['image'], #1 'pid': request.GET['pid'], #2 } if 'cart_data_obj' in request.session: if str(request.GET['id']) in request.session['cart_data_obj']: cart_data= request.session['cart_data_obj'] cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty']) cart_data.update(cart_data) request.session['cart_data_obj']=cart_data else: cart_data=request.session['cart_data_obj'] cart_data.update(cart_product) request.session['cart_data_obj']=cart_data request.session['total_cart_items'] = len(cart_data) else: request.session['cart_data_obj']=cart_product request.session['total_cart_items'] = len(cart_product) return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items']}) I think the error … -
Django+Graphene Error on Unknown argument while writing mutation
I am getting this as an error import graphene from .types import ApplicationType from api.graphql.helpers.save_application_helper import save_application_helper class ApplicationMutation(graphene.Mutation): class Arguments: firstname = graphene.String() lastname = graphene.String() gender = graphene.String() district = graphene.String() pin_code = graphene.String() connection_type =graphene.String() category =graphene.String() govt_id_type =graphene.String() govt_id_number = graphene.String() load_applied = graphene.Int() application = graphene.Field(ApplicationType) @classmethod def mutate(self, info, requested_data): application = save_application_helper(requested_data) return ApplicationMutation( application = application ) my mutations.py code looks like this I tried looking at the code but I cannot find any leads on why is it behaving like this. -
Django upgrade to 4.2 admin static files issue
I am currently using django 3.2 and would like to upgrade to 4.2 soon. Doing so on a local environment and using python manage.py collectstatic works. However the problem comes when I try to deploy this to a development environment. The new admin static files are not loading which causes the django admin page to look dysfunctional. Particularly, django 4.2 introduces a dark_theme.css static file which returns a 404 error when looking at the browser network tab. On my local environment, the file returns a 200 ok. This is the most similar thread to my issue I could find on the official django forum, however there is not a clear fix for the problem (perhaps because there are a lot of reasons why the issue could be happening) I am using nginx for the server. We have a CI process that runs collectstatic then copies the output to a docker container and I have this nginx configuration to get the static files: location /static/ { autoindex on; alias /usr/share/nginx/html/static/; } In django settings, I have this configuration: STATIC_ROOT = BASE_DIR / "ui/build/static" STATIC_URL = "/static/" Such that the static files are generated at STATIC_ROOT then the docker container copies them … -
How to tie this to a specific model
I am getting this bellow error: null value in column "two_week_period_id" of relation "timesheets_usertimesheet" violates not-null constraint Which I understand because the very last null value is not being passed through. Here are my models: models.py class TwoWeekPeriod(models.Model): start_date = models.DateField(_("Start Date")) end_date = models.DateField(_("End Date")) week_number = models.IntegerField(_("Week Number")) class CreateNewTimesheet(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) start_date = models.DateField(_("Start Date")) end_date = models.DateField(_("End Date")) two_week_period = models.ForeignKey(TwoWeekPeriod, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): week_number = (self.start_date - timezone.now().date()).days // 14 + 1 two_week_period, _ = TwoWeekPeriod.objects.get_or_create( start_date=self.start_date, end_date=self.end_date, defaults={'week_number': week_number} ) self.two_week_period = two_week_period super().save(*args, **kwargs) The above created a two_week_period as an id for every two weeks entered. For example, 03/10/2024-03/14/2024 is two_week of id 1, next two week will add an id of 2 and so on. I am trying to pass the two_week_period from CreateNewTimesheet over to: simplied verion of UserTimesheet class UserTimesheet(models.Model): employee = models.ForeignKey(Employee, models.SET_NULL, blank=True, null=True) start_date = models.DateField(_("Start Date")) end_date = models.DateField(_("End Date")) two_week_period = models.ForeignKey(TwoWeekPeriod, on_delete=models.CASCADE) It seems without the two_week_period in the Usertimesheet model, I do not get this error. But I want to display the two_week_period, so that I can tie the two weeks to … -
Django e-commerce Wishlists menu list in dropdown menu on product page of currently logged in user to choose from to add the product to not working
What I'm trying to achieve is give the currently logged in user the ability to add a product to a specific wishlist that the user has made earlier. To do this I want there to be a dropdown menu button with a list of all the current wishlists the user has with a checkbox. I tried to do queryset on the form field but it wont let me filter the currently logged in user it give me the "requests not defined" error. Its not working because I believe you can't use filter to filter the user with ModelForm. What's another way of doing this? -
Django authentication user login
`I'm encountering an issue with user authentication in my Django project. I have a custom user model for doctors Doctor which inherits from AbstractUser. Despite entering the correct email and password during login, the system returns an "Invalid password" error. base/models.py from django.db import models from django.contrib.auth.models import AbstractUser, Group, Permission class Doctor(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=50) name = models.CharField(max_length=50) profession = models.CharField(max_length=50, default='Doctor') email = models.EmailField(max_length=254, unique=True) emp_code = models.CharField(max_length=50) password = models.TextField(max_length=150) USERNAME_FIELD = 'email' groups = models.ManyToManyField( Group, blank=True, related_name='doctor_group' ) user_permissions = models.ManyToManyField( Permission, blank=True, related_name='doctor_user_permission' ) def __str__(self): return self.username base/views.py def docter_login(request): if request.method == 'POST': email = request.POST.get('email').lower() password = request.POST.get('password') print(email,password) # Authenticate the user using the email and password provided in the form if not Doctor.objects.filter(email__iexact=email).exists(): messages.error(request, 'User with that email Does not exists.') return render(request, 'base/error.html') user = authenticate(request, email=email, password=password) if user is not None and user.is_doctor: login(request, user) return redirect('home') else: messages.error(request,'Invalid password.') return render(request, 'base/error.html') return render(request, 'base/doctor_login.html') the user exists and passing the correct credentials to authenticate, it's still returning "Invalid password". What could be causing this issue? `