Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Staging and Production Environment on Digitalocean
I was wondering what the best practise is of having a staging and a production environment on digitalocean. Goal is to test the website with the same environment (with same libs, nginx configs etc.) as in the production environment, before finally taking the project to production. One solution for me would be to create a copy of the existing droplet (shut down of current droplet, take a snapshot and then copy the image-snapshot to new droplet) and then using this staging environment for testing. My questions are: Is this considered a good practise? Are there any alternatives and tools that could make it easier? Are two GitHub instances necessary? What else should I consider, when having two droplets with two IP addresses (performance, costs, safety etc.)? Also, FYI I am using Django as my web framework and Ubuntu 18.04.3 (LTS) x64 as my server. What is more, a local environment exist too. Thank you. -
Accessing nested values in Django
I am trying to access values in my Django template (using Jinja2) from an API and am struggling quite a bit. I'm new to Python/Django/programming and am having a hard time navigating through this complex nested structure of lists/dicts. Here is a snippet of the API response for a single flight (the response contains a total of 250 flights): { "meta": { "count": 2 }, "data": [ { "type": "flight-offer", "id": "1", "source": "GDS", "instantTicketingRequired": false, "nonHomogeneous": false, "oneWay": false, "lastTicketingDate": "2020-11-20", "numberOfBookableSeats": 2, "itineraries": [ { "duration": "PT22H40M", "segments": [ { "departure": { "iataCode": "GIG", "terminal": "2", "at": "2020-12-01T16:30:00" }, "arrival": { "iataCode": "CDG", "terminal": "2E", "at": "2020-12-02T07:45:00" }, "carrierCode": "AF", "number": "443", "aircraft": { "code": "77W" }, "operating": { "carrierCode": "AF" }, "duration": "PT11H15M", "id": "3", "numberOfStops": 0, "blacklistedInEU": false }, { "departure": {... For each flight I would like to extract the following key/values: id duration iataCode Below is what I have tried so far... id (successful) {% for flight in data %} {{ flight.id }} {% endfor %} iataCode (unsuccessful) {% for flight in data %} {% for itinerary in itineraries %} {% for segment in segments %} {{ departure.iataCode }} {% endfor %} {% endfor … -
How to get data from nested field in Django Raw Query?
I have problem to fetch the foreign key data from a field with my raw queryset in django This is my Raw Queryset: query = "SELECT * FROM assets WHERE MBRContains(ST_GeomFromText('Polygon((%s))'), point(lat, lon));" % polygon asset = Asset.objects.raw(query) and the result is like this: { owner: "c9e35046-ec42-4264-a72c-b4258a0be586" point_of_interests: ["acc0df64-f9c4-41b5-b54e-236bbfc9d446", "66cb6541-6cc8-40c0-b91d-a8f410626cb1",…] 0: "acc0df64-f9c4-41b5-b54e-236bbfc9d446" 1: "66cb6541-6cc8-40c0-b91d-a8f410626cb1" } I want to get the point_of_interest data such name and etc, not just the id of the point_of_interest. How can I achieve that ? -
How to display image in django using HttpResponse
I am trying to display the image of python script output using below lines but instead of displaying in browser, code downloading the file instead of displaying this is the function i have created in views.py: def adc(request): file = "C:\Users\TheBoss\Downloads\New_test.xlsx" df = pd.read_excel(file, sheet_name='Graph') plt.plot(df['Date'], df['Video Device - Not Responding'], label = 'Video Device - Not Responding') #plt.plot(df['Date'], df['30th Apr'], 'b', label = '30-Apr') plt.xticks(rotation=45) plt.tick_params(axis='x', which='major', labelsize=6) # naming the y axis plt.ylabel('Condition Count') # giving a title to my graph plt.title('Condition') # function to show the plot plt.legend() #plt.show() plt.savefig('C:\\Users\\TheBoss\\Downloads\\test.png') image_data = open("C:\\Users\\TheBoss\\Downloads\\test.png", "rb").read() return HttpResponse(image_data, content_type="test/png") -
Safari only CORS origin django issue - Origin is not allowed by Access-Control-Allow-Origin - django-cors-headers
[Error] Origin https://www.rrrroll.com is not allowed by Access-Control-Allow-Origin. [Error] XMLHttpRequest cannot load https://www.backend.rrrroll.com/upload/ due to access control checks. [Error] Failed to load resource: Origin https://www.rrrroll.com is not allowed by Access-Control-Allow-Origin. (upload, line 0) Having CORS issues with Safari only - Firefox, Chrome OK. Works in development for Safari but not production. Any help? Only difference is the backend is served on a subdomain in prod rather than just a different localhost port in dev. Django as backend for Next.js frontend, the GraphQL POST endpoint works fine on Safari, but the POST /upload endpoint gives the errors above. Using the django-cors-headers package and the CORS_ALLOWED_ORIGINS is correctly set. I previously did have a similar error earlier with another project and Safari this year and setting the CORS_ALLOW_ALL_ORIGINS and explicitly stating the default allowed headers worked. Not working in this case. Worth noting that a preflight OPTIONS request is run with 200 response when I press the upload the button I believe Nov 15 00:32:19 ubuntu-s-1vcpu-1gb-lon1-01 gunicorn[16665]: - - [15/Nov/2020:00:32:19 +0000] "OPTIONS /upload/ HTTP/1.0" 200 0 "https://rrrroll.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15" See the massive difference in requests on Safari vs Chrome, for some … -
Django - Enter a list of values - ForeignKey
For a M2O relation what field should I be using in forms? models.py class Studio(models.Model): name = models.SlugField(max_length=100) rating = models.CharField(max_length=10, default=None) def __str__(self): return self.name class AnimeDetail(models.Model): title_japanese = models.CharField(max_length=250) studio = models.ForeignKey(Studio, on_delete=models.CASCADE, default=None) ... forms.py from .models import AnimeDetail class AnimeDetailForm(forms.ModelForm): class Meta: model = AnimeDetail fields = ['icon', 'image', 'title_japanese', 'title_english', 'studio', 'genre', 'total_episodes', 'posted_episodes', 'season', 'date_started', 'date_finished', 'status', 'type_anime', 'age', 'source'] widgets = { 'title_japanese': forms.TextInput(attrs={'class': 'form-control'}), 'studio':forms.Select(attrs={'class': 'form-control'}), ... } 'studio':forms.Select(attrs={'class': 'form-control'}) -> Select doesnt work properly in this situiation but in other project worked without problems. Error: What is wrong? -
psycopg2.OperationalError: could not translate host name 'db' (While name 'db' is pingable in container)
There's a lot of dated information out there on similar issues, which I all went through. I'm running docker-compose file version 3.8. My issue is that: psycopg2 or Django can not resolve my database's container name. However, I can after a docker-compose up: gerard@solace ~$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 21bcbcc35083 project_web "/app/entrypoint.sh …" 6 seconds ago Up 6 seconds 0.0.0.0:8006->8000/tcp project_web_1 a92e3e98477f postgres:12.0-alpine "docker-entrypoint.s…" 7 seconds ago Up 6 seconds 0.0.0.0:5432->5432/tcp project_db_1 gerard@solace ~$ docker exec -it project_web_1 ping -c 2 db PING db (172.25.0.2): 56 data bytes 64 bytes from 172.25.0.2: seq=0 ttl=64 time=0.078 ms 64 bytes from 172.25.0.2: seq=1 ttl=64 time=0.302 ms --- db ping statistics --- 2 packets transmitted, 2 packets received, 0% packet loss round-trip min/avg/max = 0.078/0.190/0.302 ms``` Also, my entrypoint.sh connects before continuing, and does continu so host and port seems accessible: Entrypoint snippet: while ! nc -z $SQL_HOST $SQL_PORT; do sleep 1 done What am I missing? -
Why django records test data into the database
I need to record some data within my test module to use it during my unit tests. After tests, I notice that these records remain within the database even if I get the following message after tests: Destroying test database for alias 'default'... I am currently using sqlite engine, would it explain such behavior? What would be the best practice here? -
dynamic appointment-pricing with django
I have an appointment app that allows clients to create doctor appointments. An admin would then award the appointment to available doctors. Part of the app reads as follows: class Appointment(models.Model): client = models.ForeignKey(User, on_delete=models.CASCADE) appointment_day = models.DateField(validators=[present_or_future_date]) appointment_time = models.TimeField() service_needed = MultiSelectField(choices=MEDICAL_SERVICES_CHOICES, null=True, blank=True) With MEDICAL_SERVICES_CHOICES, clients can choose between: radiology appointments, dentist appointments, etc.. CHALLENGE: I need to be add a system-defined pricing attribute. The problem is that each appointment is created by the client & not the hospital. Furthermore, I need to establish different prices for each of the MEDICAL_SERVICES_CHOICES. QUESTIONS How do I automatically add a service-cost/price field on each appointment? Is there a better way to do this? (I've considered going with an e-commerce model except with services rather than products: Not sure if this would be better though!) -
How to add an object to a manytomany field in django
I have two models (Group and Contact). A Group can have many Contacts and a Contact can be in many Groups. I can create contacts but I can´t create groups right now. When I validate form.is_valid() it returns false and the error I'm getting is {'contacts': [ValidationError(['Enter a list of values.'])]} What am I missing here? models.py class Contact(models.Model): # Fields first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=32) contacts = models.ManyToManyField(Contact, related_name='groups') forms.py class CreateGroupForm(ModelForm): class Meta: model = Group fields = ["name", "contacts"] widgets = { 'name': TextInput(attrs={ "placeholder" : "", "class": "form-control" }), 'contacts': Select(attrs={ "placeholder" : "", "class": "form-control" }) } class CreateContactForm(ModelForm): class Meta: model = Contact fields = "__all__" widgets = { 'first_name': TextInput(attrs={ "placeholder" : "Nombre", "class": "form-control" }), 'last_name': TextInput(attrs={ "placeholder" : "Apellido", "class": "form-control" }) } views.py def create_group(request): if request.method == "POST": form = CreateGroupForm(request.POST) if form.is_valid(): group = form.save(commit=False) group.save() else: print(form.errors.as_data()) form = CreateGroupForm() return render(request, 'create-group.html', {'form':form}) elif request.method == "GET": form = CreateGroupForm(request.POST or None) return render(request, "create-group.html", { 'form' : form}) -
Django app on Heroku: migrations reset "relation already exists" error
I have a Django app running on Heroku. I deploy it via Github. I had to return to a previous commit and now I get the following error when I try to update Heroku: django.db.utils.ProgrammingError: relation "catalog_productosbase_image_gallery" already exists Tryied reseting migrations I tried to reset all migrations: Removed all migration files from app folder (except init) Removed the db.sqlite3 file Ran makemigrations Ran migrate --fake-initial Ran migrate Localy everything goes fine, then I did: git add -A git commit -m "name" git push origin master git push heroku master Here is where I get the relation already exists error. Procfile The Procfile inlcudes: release: python manage.py migrate Also tryied release: python manage.py migrate --fake-initialwith the same resut. Local showmigrations admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions catalog [X] 0001_initial [X] 0002_auto_20201115_0948 contenttypes [X] 0001_initial [X] 0002_remove_content_type_name covid (no migrations) fulberg (no migrations) sessions [X] 0001_initial sites [X] 0001_initial [X] 0002_alter_domain_unique stockbucket [X] 0001_initial website (no migrations) Server showmigrations admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null … -
product is not adding to cart properly
I am making a commerce website using django. I used session to fetch all the request in my project, but I am facing an issue. The problem is when I add a product to my cart it added successfully but whenever I try to another in the same time it shows 0 product in cart. I can't even add the amount but when I remove the first product the quantity automatically added to the second product. Really confusing, and for that reason I am providing screenshots. Here is my Views.py: class Index(View): def get(self, request): cart = request.session.get('cart') if not cart: request.session['cart'] = {} products = None cats = Category.get_categories() brands = Brand.get_brands() categoryID = request.GET.get('category') brandID = request.GET.get('brand') if categoryID: products = Product.get_products_by_category(categoryID) else: products = Product.get_all_products() if brandID: proucts = Product.get_brands_by_products(brandID) else: products = Product.get_all_products() args = { 'products':products, 'cats': cats, 'brands': brands } return render(request, 'Home/index.html', args) def post(self, request): product = request.POST.get('product') print(product) cart = request.session.get('cart') remove = request.POST.get('remove') if cart: quantity = cart.get(product) if quantity: if remove: if quantity <= 1: cart.pop(product) else: cart[product] = quantity-1 else: cart[product] = quantity+1 else: cart[product] = 1 else: cart = {} cart[product] = 1 request.session['cart'] = cart print('cart', … -
JS always loads default view
I'm taking the CS50 course "Web Programming with Python and Javascript", so I'm pretty new to all this stuff, especially to Javascript. In one of the projects that need to be done, one have to implement a social network plattform where users can post some texts, like and dislike them and follow other users. There are 3 routes a user can go: All posts, Following and users posts. I've been trying to solve this with js front end. I've a function "view_posts", that takes an argument that specifies what posts should be fetched and rendered to the html page. Consider the folling part of my js file: document.addEventListener('DOMContentLoaded', function() { username = document.getElementById('username').innerText document.querySelector('#posts').addEventListener('click', () => view_posts('all')); document.querySelector('#username').addEventListener('click', () => view_posts(username)); document.querySelector('#following').addEventListener('click', () => view_posts('followers')); document.querySelector('#post-form').style.display = "none"; view_posts('all') }); Fetching the data is basically working, but js is always displaying the default view "view_posts('all')". Meaning, even if I click on the element whose id is #post, calling the very same function including the same argument, the function is called without displaying anything, before it calls the default view again (this time it will display the data correct). Here is the function: function view_posts(selector){ // document.querySelector('#post-form').style.display = "none"; if (selector … -
getting logfile error permission denied . what does it mean?
I am getting below error when I run the command python3 manage.py makemigrations When I tried on my local system then also I was getting same error but when I delete logs/logfile and create new then I works good for me. Now When I tried on my server console then I got below Error (app-env) chalil@ip-172-31-5-73:~$ python3 manage.py migrate Traceback (most recent call last): File "/usr/local/lib/python3.6/logging/config.py", line 558, in configure handler = self.configure_handler(handlers[name]) File "/usr/local/lib/python3.6/logging/config.py", line 731, in configure_handler result = factory(**kwargs) File "/usr/local/lib/python3.6/logging/handlers.py", line 150, in __init__ BaseRotatingHandler.__init__(self, filename, mode, encoding, delay) File "/usr/local/lib/python3.6/logging/handlers.py", line 57, in __init__ logging.FileHandler.__init__(self, filename, mode, encoding, delay) File "/usr/local/lib/python3.6/logging/__init__.py", line 1031, in __init__ StreamHandler.__init__(self, self._open()) File "/usr/local/lib/python3.6/logging/__init__.py", line 1060, in _open return open(self.baseFilename, self.mode, encoding=self.encoding) PermissionError: [Errno 13] Permission denied: '/webapps/app/logs/logfile' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/webapps/app/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/webapps/app/lib/python3.6/site-packages/django/core/management/__init__.py", line 325, in execute settings.INSTALLED_APPS File "/webapps/app/lib/python3.6/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/webapps/app/lib/python3.6/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/webapps/app/lib/python3.6/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in … -
Cannot assign "(<department: department object (1)>,)": "internal_information.department" must be a "department" instance
i used postman to create and update model data , my create function can work but my update cant, i get a error "Cannot assign "(<department: department object (1)>,)": "internal_information.department" must be a "department" instance." my_api_view_createmy_api_view_updatemy_modelmy_serializermy_error -
Is possible Django CRUD operation without using model forms?
I am creating a Registration app in django where I want to update user info after login. I am using bootstrap forms. Is possible Django CRUD operation without using model forms? I created user like this: def handleRegister(request): if request.method == 'POST': username = request.POST['username'] fname = request.POST['fname'] lname = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] # check erronous inputs if len(username) > 10: messages.error(request, "Username should be less than 10 chracters") return redirect('/') if pass1 != pass2: messages.error(request, "Passwords do not match") return redirect('/') if not username.isalnum(): messages.error(request, "Username should be alphanumeric") return redirect('/') # creating user here myuser = User.objects.create_user(username, email, pass1) #creating user with the help of User(you have to import it. from django.contrib.auth.models import User) myuser.first_name = fname myuser.last_name = lname myuser.save() # saving created user messages.success(request, "Your account has been created sucessfully") return redirect('/') else: return HttpResponse("404 not found") is there any method like above where I can update user info? -
Why does my website keep on having Privacy issue?
Does anyone know the reason for Privacy Issue? But it only happens on my website url without the ("www").For example, when accessing the url https://mywebsite.com, it shows the "Your connection is not private" sometimes. But my SSL certificate is still valid and not yet expired. But when I access the full url, https://www.mywebsite.com, there is no privacy issue. I hope someone can help me. Thank you. -
Getting the value of select option Django
Im been having a trouble how can I get the the value of my select option, I been using javascript to set the value of select option, below is my code which is returning the province value to number instead of text. The problem is how can I convert the number to text, is there any expert who share solution about this. views.py def sample_data(request): if request.method=='POST': province = request.POST['list1'] print(province) #return ex. 2 depend on select value return render (request,'sample.html') Select option - my reference link <select id="list1" name ="list1" onchange="updateList('list2', this);"></select> <select id="list2" name ="list2" onchange="updateList('list3', this);"></select>> <select id="list3" name ="list3"></select> javascript let data = [{"id":1,"name":"USA","parentid":0}, {"id":2,"name":"Japan","parentid":0}, {"id":3,"name":"Europe","parentid":0}, {"id":4,"name":"California","parentid":1}, {"id":5,"name":"Oklahoma","parentid":1}, {"id":6,"name":"Arizona","parentid":1}, {"id":7,"name":"Kantô","parentid":2}, {"id":8,"name":"Kansai","parentid":2}, {"id":9,"name":"Chügoku","parentid":2}, {"id":10,"name":"France","parentid":3}, {"id":11,"name":"Deutschland","parentid":3}, {"id":12,"name":"Espana","parentid":3}, {"id":13,"name":"Sacramento","parentid":4}, {"id":14,"name":"Los Angeles","parentid":4}, {"id":15,"name":"San Diego","parentid":4}, {"id":16,"name":"Tulsa","parentid":5}, {"id":17,"name":"Oklahoma City","parentid":5}, {"id":18,"name":"Lawton","parentid":5}, {"id":19,"name":"Phoenix","parentid":6}, {"id":20,"name":"Flagstaff","parentid":6}, {"id":21,"name":"Tucson","parentid":6}, {"id":21,"name":"Tokyo","parentid":7}, {"id":22,"name":"Chiba","parentid":7}, {"id":23,"name":"Tochigi","parentid":7}, {"id":24,"name":"Kyoto","parentid":8}, {"id":25,"name":"Osaka","parentid":8}, {"id":26,"name":"Nara","parentid":8}, {"id":27,"name":"Tottori","parentid":9}, {"id":28,"name":"Hirochima","parentid":9}, {"id":29,"name":"Okayama","parentid":9}, {"id":30,"name":"Quimper","parentid":10}, {"id":31,"name":"Toulouse","parentid":10}, {"id":32,"name":"Nancy","parentid":10}, {"id":33,"name":"Dusseldorf","parentid":11}, {"id":34,"name":"Leipzig","parentid":11}, {"id":35,"name":"Munchen","parentid":11}, {"id":36,"name":"Barcelona","parentid":12}, {"id":37,"name":"Sevilla","parentid":12}, {"id":38,"name":"Guernica","parentid":12}] function populateList(list, pid) { let l = document.getElementById(list); l.innerHTML = ""; let topItem = document.createElement("option"); topItem.value = 0; topItem.text = "--Select--"; l.appendChild(topItem); let items = data.filter(item => item.parentid == pid); items.forEach(function(item){ let newItem = document.createElement("option"); newItem.value = item.id; newItem.text = item.name; l.appendChild(newItem); }) } function updateList(selList, thisList) { if (thisList.value != … -
Django: Select from the dropdown the object that has the field is_active=True
i'm a newbie using django and i have a problem that cannot solve. In my ServiceCreateView i need to select from the dropdown the object car that has the field is_active = true, how can i acomplish that? class Car(models.Model): brand = models.charfield(...) is_active= models.BooleanField(default=True) class Service(models.Model): car = models.ForeingKey('Car'....) name = models.Charfield() class ServiceCreateView(CreateView): model = Service form = ServiceForm ... If i change the field is_active to false in Car model, should not be shown in the dropdown. can someone put me in the right direction? -
Errors when passing a list through URL in Django
I try to pass a list through an URL in Django. I found this: Passing a list through url in django But I still get Errors. I feel like Iam running in a circle. My urls: path('query/', include(('query.urls', 'query-space'), namespace='query-space')), re_path(r'^2/(?P<amb_list>\w+)/$',views.ambitionGenPage, name='userambitiongen'), My views: def ambitionPage(request): if request.method == 'POST': form = AmbitionForm(request.POST) if form.is_valid(): ambs_list = form.cleaned_data['ambition_field'] redirect = HttpResponseRedirect(reverse('query-space:userambitiongen')) redirect['Location'] += '&'.join(['ambs={}'.format(x) for x in ambs_list]) return redirect form = AmbitionForm() return render(request, 'query/ambition.html',{'form':form,}) def ambitionGenPage(request): ambitions = request.GET.getlist('amb_list') if ambitions: ambitions = [int(x) for x in ambitions] print(ambitions) #I first want to check what data I get return render(request, 'query/ambitionGen.html',{}) I adapted the code of the link. In the line: redirect = HttpResponseRedirect(reverse('query-space:userambitiongen', args=(amb_list))) he doesnt know the argument: NameError: name 'amb_list' is not defined In the example there is no argument. When I try this I get the error: Reverse for 'userambitiongen' with no arguments not found. 1 pattern(s) tried: ['query/2/(?P<amb_list>\\w+)/$'] I also found nothing in the internet to this expression: redirect['Location'] Could someone explain to me what ['Location'] stands for? What would be the right solution? I tried to find it by myself in many hours. Thank you very much for your time! -
Django save() method won't save my forms and can't create a new instance
I want to save 2 forms in my django view: def create_model(request): context = { 'form_one' : Register_modelOne(prefix = 'form_one'), 'form_two' : Register_modelTwo(prefix = 'form_two'), } if request.method == "POST": form_one = Register_modelOne(request.POST, prefix = 'form_one') form_two = Register_modelTwo(request.POST, prefix = 'form_two') if form_one.is_valid() and form_two.is_valid(): form_one.save() form_two.save() ParentModel.objects.create(name = 'mymodel', element_one = form_one, element_two = form_two) The whole point is to create a new ParentModel which has a manyToMany() relation with both modelOne and modelTwo. But Django won't save it in my database this way. Does anyone have any idea why? (also even form_one and form_two are not saved in the database with this method) note: This is connected to my question in Another Question -
Django template - How to get key, value(list) from a dictionary in the request context
I have my context in a html template and I'm not able to read the value which is a List of objects from key in my dictionary. This is my context: {'month_posts': defaultdict(<class 'list'>, {'October': [<Post: Set pagination>, <Post: Test pagination>], 'November': [<Post: Redesign Model>]} ) } This is the for loop I'm implementing to get the key and value: {% for month, posts in month_posts.items %} ... <h3>{{ month | capfirst }}</h3> {% for post in month_posts[month] %} <a href="#">{{ post.title }}</a> {% endfor %} ... {% endfor %} I got this error: Could not parse the remainder: '[month]' from 'month_posts[month]' I have tried these: {% for month in month_posts %} I got no errors but also no data in my template. Do you have any idea how I could get the List in the value of the Dictionary? Thanks. -
Not able to insert data into database using Django
I am a beginner in Django and I am trying to insert values into the auth_user table. But somehow I am not able to do so. I tried to resolve but everything seems to go in vain. Here is my views.py: from django.shortcuts import render,redirect from django.contrib.auth.models import User, auth # Create your views here. def register(request): if request.method == 'POST' : firstname = request.POST['firstname'] lastname = request.POST[ 'lastname'] emailid= request.POST['emailid'] username= firstname+lastname passwordl = request.POST['password'] user = User.objects.create_user(username=username,first_name=firstname,last_name=lastname) user.save() return redirect('admin/') else: return render(request, 'employee/register.html') This the urls.py from django.urls import path from . import views urlpatterns = [ path('register/', views.register, name='register'), ] I can also notice than when I click register button I get an error that employee\register\register was called which doesnt exist, which is strange as employee\register is to be fetched. -
How to pass currently user ID/PK from view to form in Django?
The problem I'm having is I'm trying to create a form which passes the currently logged-in users ID by embedding it within a hidden field in a ModelForm. Models.py class UserPhotos(models.Model): user = models.ForeignKey(NewUser, on_delete=models.CASCADE) #photos = models.ImageField(height_field=1350, width_field=1080) description = models.CharField(max_length=200) date = models.DateTimeField(auto_now=True) class Meta: '''Change plural name''' verbose_name_plural = 'Photos' Forms.py class AddPhotos(forms.ModelForm): user = forms.CharField(widget = forms.HiddenInput(), required=False) class Meta: model = UserPhotos fields = ( 'description','user', ) Views.py def add_photo(request): context = {} user = request.user if not user.is_authenticated: return redirect('my_app:login',) if request.POST: form = AddPhotos(request.POST) if form.is_valid(): form.save(commit=False) form.user=request.user form.save return redirect('/') else: context['photoAdd_form'] = form else: form = AddPhotos() context['photoAdd_form'] = form return render(request, 'main/photo_add.html', context) I have tried something like this It's works, but I have no idea how to pass the ID to the init. It gave me a error : KeyError at /add 'userID' Forms.py ... def __init__(self, *args, **kwargs): #It is works but how will i pass the data request = kwargs.pop('userId') print(request) super(AddPhotos, self).__init__(*args, **kwargs) self.fields['user'].initial = request.user Views.py def add_photo(request): context = {} user = request.user if not user.is_authenticated: return redirect('my_app:login',) if request.POST: form = AddPhotos(request.POST, userId = request.user.id) ... -
django autotranslate gives an error "IndexError:list index out of range"
I have configured django autotranslate as per the direction on the pypi page but when I try to run the translate_messages command, it throws back an error return lambda: self._basic_translate(text, target_language, source_lauguage)[0] File "C:\Users\Richards\AppData\Local\Programs\Python\Python38\lib\site-packages\goslate.py", line 253, in _basic_translate data = {'src': raw_data[-1][0][0]} IndexError: list index out of range I dont have have a explicit list in my project, just querysets and its quite numerous. please help me on this