Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Browser back button scenario in Django Application
Please help me on the below scenario: i have created a django form,after filling the form there is chance the user may press the back button,at this point ,it should pop-up a message saying save or cancel the form.when i say "save" the form should submit and when i say cancel it should go to the previous page. after research,i understand javascript helps on this requirement,but i didnt find the related one to guide me. wat i need to add in my view and in my html code. how can i achieve ,iam a beginner in coding and also asking questions in stackoverflow. views.py def create(request): context = {} testlogFormset = modelformset_factory(testlogs, form=testlogForm) form = shoporderForm(request.POST or None) formset = testlogFormset(request.POST or None, queryset= testlogs.objects.none(), prefix='testlogs') # if request.method == "POST": if form.is_valid() and formset.is_valid(): with transaction.atomic(): shoporder_inst = form.save(commit=False) shoporder_inst.save() for mark in formset: data = mark.save(commit=False) data.shoporderno = shoporder_inst data.save() return redirect("/create") context['formset'] = formset context['form'] = form return render(request, 'prod_orders/create.html', context) -
Updating required ImageField from URLField (as option)
Given the setup below, is it possible to offer an optional, "virtual" URLField, that will set a required ImageField if the latter is not supplied? class ReleaseImage(models.Model): release = models.ForeignKey(Release, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/releases') class ReleaseImageForm(forms.ModelForm): image_from_url = forms.URLField(required=False) class Meta: fields = '__all__' model = ReleaseImage class ReleaseImageAdmin(admin.ModelAdmin): form = ReleaseImageForm I have attempted some different methods, without success, e.g. overriding clean on the ModelForm as below, but the form is not validated (complaining that image is required). def clean(self): super().clean() # ... download image from url ... image = SimpleUploadedFile(name="foo.jpg", content=bytes_downloaded_from_url) self.cleaned_data["image"] = image # self.instance.image = image # also attempted ... return self.cleaned_data What would be the best way of doing this? I'm getting somewhat confused whether this should live in save, clean, or clean_FOO, in the model, the modeladmin or the modelform -- or a combination of this somehow`? -
ajax call to filter select field in django
I have a form with two fields related to each other and I want the rooms filtered based on the class in the front form this is my code models.py class Class(models.Model): class_name = models.CharField(max_length=100) def __str__(self): return self.class_name class Room(models.Model): room_name = models.CharField(max_length=100) class = models.ForeignKey(Class,related_name='class',on_delete=models.SET_NULL, null=True) def __str__(self): return self.room_name views.py class CustomFormView(LoginMixin, TemplateView): template_name = 'form.html' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) context['class'] = Class.objects.values('pk','class_name') context['rooms'] = Room.objects.all() return self.render_to_response(context) def get_related_rooms(request): class_id = request.GET.get('class_id') rooms = Room.objects.filter(class_id=class_id) return render(request, 'form.html', {'rooms': rooms}) form.html <form id="custom_form" data-rooms-url="{% url 'app:get_related_rooms' %}"> Class Name: <select type="text" class="form-control"id="class_name" name="class_name"> {% for c in class %} <option value="{{ c.pk }}">{{ c.class_name }}</option> {% endfor %} </select> Room Name: </label> <select type="text" class="form-control" id="room_name" name="room_name"> {% for r in rooms %} <option value="{{ r.pk }}">{{ r.room_name }}</option> {% endfor %} </select> </form> //here is the ajax call to get the rooms <script> document.getElementById("#class_name").change(function () { var url = $("#custom_form").attr("data-rooms-url"); var classId = $(this).val(); $.ajax({ url: url , method: 'GET', data: { 'class_id': classId }, success: function (data) { $("#room_name").html(data); } }) }); </script> I want to make this: When I choose the class in the first select I want to … -
How to install mod_wsgi on aws linux 2
I am trying to install mod-wsgi on Linux 2. But I am getting this error error: command 'gcc' failed with exit status 1 ERROR: Command errored out with exit status 1: /home/ec2-user/venv/bin/python3.7 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-jzcb7l6h/mod-wsgi/setup.py'"'"'; __file__='"'"'/tmp/pip-install-jzcb7l6h/mod-wsgi/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-zrs06wit/install-record.txt --single-version-externally-managed --compile --install-headers /home/ec2-user/venv/include/site/python3.7/mod-wsgi Check the logs for full command output. This is what I have tried yum install gcc openssl-devel bzip2-devel libffi-devel zlib-devel cd /usr/src sudo wget https://www.python.org/ftp/python/3.7.9/Python-3.7.9.tgz sudo tar zxvf Python-3.7.9.tgz ./configure --enable-shared ./configure --enable-optimizations #sudo make sudo make altinstall python3.7 --version cd ~ python3.7 -m venv venv source venv/bin/activate sudo yum update httpd sudo yum install httpd sudo yum install httpd-devel pip install mod-wsgi -
Django - Filter based on href?
Is there a way to filter based on the href contents? I have a .html page that has a link <td><a href="{% url 'ipDATA' %}">{{item.IP_Address}}</td> I have a function like this: def ipDATA(request, Host=IPs.IP_Address): items = NessusReports.objects.filter() context = { 'items': items, } return render(request, 'nessusdata.html', context) Right now, it returns the entire table, I want to filter based on the href. -
make staff user not edit superuser's username
In my django-admin panel i'm trying to make that the staff-user can make new user-accounts where it needs to add a username but the staff-user shouldn't be abel to edit the superuser's username. Right now this doesn't happens with the code. admin.py from typing import Set from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin # Unregister the provided model admin admin.site.unregister(User) # Register out own model admin @admin.register(User) class CustomUserAdmin(UserAdmin): def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) is_superuser = request.user.is_superuser is_staff = request.user.is_staff disabled_fields = set() # type: Set[str] if not is_superuser: disabled_fields |= { 'is_superuser', 'user_permissions', 'is_staff', 'date_joined', } # Prevent non-superusers from editing their own permissions if ( not is_superuser and obj is not None and obj == request.user ): disabled_fields |= { 'is_staff', 'is_superuser', 'groups', 'user_permissions', 'username', } for f in disabled_fields: if f in form.base_fields: form.base_fields[f].disabled = True return form # No delete button def has_delete_permission(self, request, obj=None): return False -
How do I fix these errors when installing a plugin for python bot?
I'm attempting to use Bots Open Source EDI Translator on my Mac, and successfully ran the webserver and monitor according to their guide*, but I receive this error whenever I try to read a plugin. Server Error (500) Traceback (most recent call last): File "/Users/myusername/Documents/Work/Python/bots_edi/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/myusername/Documents/Work/Python/bots_edi/venv/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/myusername/Documents/Work/Python/bots_edi/bots-3.2.0/bots/views.py", line 447, in plugin notification = -(u'Error reading plugin:"%s".')%unicode(msg) TypeError: bad operand type for unary -: 'unicode' *I did make some adjustments when following the installation guide. I created my virtual environment to operate with Python2.7, and when I tried to run the permissions line: sudo chown -R myusername /usr/lib/python2.7/site-packages/bots, it could not find the file. I'm assuming that's because I'm running a virtual environment, so I skipped it. Perhaps that's what's causing the issues now? If so, how do I manage my virtual environment with the sudo commands? Should I somehow be installing the dependencies (cherrypy, django, genshi) inside my virtual environment? -
Best way to serve npm packages with django?
I am using django as a backend with a few js packages installed with npm. I am currently accessing the packages by allowing django to serve /node_modules by adding it to the STATICFILES_DIRS. This has been working, but I have to go in the pacakge and find the js file I want to point to and then load it using a <script src="{% static .... This is a bit tedious and seems a bit "hacky." I also cannot figure out how to use imports/requires inside my js files. Is there a way to use imports or am I stuck loading everyting via script tags? I assume this is because django doesn't know how to server the npm packages appropriately? I've read a bit into webpack and I'm still unsure if webpack is a solution to my problem. Any advice? -
Running both Django and PHP on IIS (Internet Information Services) server
I have a previous application done with PHP and I have created another django project. I'm trying to run them both on IIS server as the existing PHP project is served through IIS. When I'm running PHP and Django separately, its working fine but if I configure IIS for running django and then go to the url of the php file (localhost/test.php), its testing for the route in urls.py and returning the possible urls like /home, /about. I need to display django views while visiting URLs in the urls.py and run php file while visiting the php url. Is there any way that I can do this? Any answer is appreciable. Thanks in Advance :) -
gunicorn.socket: Failed with result 'service-start-limit-hit '
I'm having this issue when I trying to deploy my app. Any ideas what could be?= -
Django create a models.ManyToMany and models.ForeignKey to the same table
All, I'm trying to configure my Django models.py file to include 2 tables with a ManyToMany and a ForeignKey link between the 2. The current configuration with only one entry works fine: Current models.py file: from django.db import models class CustTeamMembers(models.Model): member_first_name = models.CharField(max_length = 100) member_last_name = models.CharField(max_length = 100) member_email = models.EmailField(unique=True) member_phone = models.CharField(max_length = 25, blank=True) class Meta(object): ordering = ['member_last_name'] def __str__(self): return self.member_first_name + ' ' + self.member_last_name class CustTeamName(models.Model): cust_name = models.CharField(max_length = 100) cust_members = models.ManyToManyField(CustTeamMembers, blank=True) cust_meet = models.CharField(max_length = 40, blank=True) cust_status = models.TextField(blank=True) def __str__(self): return self.cust_name def get_members(self): return ", ".join([str(p) for p in self.cust_members.all()]) I would like to add another field above the "cust_members" entry. The reason for this is I have teams with multiple members and one of them is the lead for the team. I tried the following, but it failed: Alternate models.py file: from django.db import models class CustTeamMembers(models.Model): member_first_name = models.CharField(max_length = 100) member_last_name = models.CharField(max_length = 100) member_email = models.EmailField(unique=True) member_phone = models.CharField(max_length = 25, blank=True) class Meta(object): ordering = ['member_last_name'] def __str__(self): return self.member_first_name + ' ' + self.member_last_name class CustTeamName(models.Model): cust_name = models.CharField(max_length = 100) cust_lead = models.ForeignKey(CustTeamMembers, on_delete=models.CASCADE, blank=True) … -
Fetch data in many-many relationship in a single row
These are my models Team Table class Team(CommonModel): ****Other Fields**** name = models.CharField() game = models.ManyToManyField(Game, through='Team_Game') Mapper Table class Team_Game(CommonModel): game = models.ForeignKey(Game, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) status = models.SmallIntegerField(default=1) class Meta: db_table = 'team_game' Game Table class Game(CommonModel): name = models.CharField(max_length=128, blank=False, null=False, unique=True) status = models.SmallIntegerField(default=1) I want to retrieve team with id 1 and game associated with it Expected data: team.name, other_team_cols, [game_id1, game_id2] Query: team_data = Team.objects.filter(id=1).values('id', 'name', 'game__name') Output: [ { "id": "1", "name": 'abc', "game__name": "game1" }, { "_packageID": "1", "name": "def", "game__name": "game2" } ] Expected Output: { "id": "1", "name": 'abc', "game__name": ["gam1", "gam2"] } -
Is this possible that we use procedures to insert data but create two models and serializers ?DRF PYTHON
Is this possible that we use procedures to insert data but create two models and serializers . to validate the data because the procedure get fields from two tables? DJANGO REST FRAMEWORK PYTHON -
How to call a function by loading a string in Django?
I'm new to Django and I'm testing, In case I have my posts.html templete and I wanted to load all posts in a summarized form on the page, however one side would load the posts with even id and the other with odd id. I did a function in views.py and wanted to load all posts in posts.html. def posted(request): posts = Album.objects.all() for post in posts: if post % 2 == 0: return render(request, """<div class="container marketing "> <div class="row mb-2 " > <div class="col-md-6"> <div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">{{ post.title }}</strong> <h3 class="mb-0">{{ post.author.get_full_name }}</h3> <div class="mb-1 text-muted">{{ post.created_at|date:'d, M Y'}}</div> <p class="card-text mb-auto">{{ post.summary|safe }}</p> <a href="/post/{{ post.pk }}" class="stretched-link">Continue reading</a> </div> <div class="col-auto d-none d-lg-block"> <img class="bd-placeholder-img" width="200" height="250" src="{{post.image.url}}" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/></img> </div> </div> </div>""",) return render(request, """<div class="col-md-6"> <div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-success">Design</strong> <h3 class="mb-0">Post title</h3> <div class="mb-1 text-muted">Nov 11</div> <p class="mb-auto">This is a wider card with supporting text below as a natural lead-in to additional … -
My Django Webblog project is not deploying on heroku
When I am trying to push my Django project on Heroku, each time it's showing this "failed to push some refs to .. " (check my provided screenshot). Even i have created a .gitignore file but even its not working. Here is the screenshot of problems -
Get django model correctly
I am trying to get the value of my model and get the values using a for loop but it gives me this I want it to print Gazou Gazou Gazou Gazou Gazou Gazou [<Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>] My views.py def watchlist(request): if request.method=='POST': name = User.objects.get(username=request.user.username) title = request.POST['title'] print(name) listing = Listing.objects.get(title=title) all_titles = Watchlist.objects.filter(name=name) print(all_titles) print(title) msg = "You already have this on your watchlist" a = [] for item in all_titles: a.append(item) print(a) if title in a: return HttpResponseRedirect(reverse("index")) else: watchlist = Watchlist.objects.create(taitle=title, name=name, title=listing) return HttpResponseRedirect(reverse("index")) else: user = request.user watchlist = Watchlist.objects.filter(name=user) return render(request, "auctions/watchlist.html", { "watchlist": watchlist }) My models.py class Watchlist(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE, null=True) taitle = models.CharField(max_length=100, null=True) title = models.ForeignKey(Listing, on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.taitle}" I am using django 1.11.29 and python 3.8.5 -
Is there a way to use a Django registered BaseSetting in a models save function?
I am overriding a model's save function to query Google's Geocoding API for the corresponding latitude/longitude coordinates to an address and save them to the model. I have registered a BaseSetting in Django admin with my API keys, and would like to access this registered setting inside my models.py to avoid hard-coding an API key. Handling it in the view is not an option given I would like to minimize the number of API calls. Here's some demo code: class DropoffLocationPage(models.Model): templates = "locations/dropoff_location_page.html" dropoff_address = models.CharField(max_length=40, blank=False, null=False) dropoff_city = models.CharField(max_length=40, blank=False, null=False) dropoff_state = models.CharField(max_length=2, blank=False, null=False) dropoff_zip = models.CharField(max_length=5, blank=False, null=False) dropoff_unit_number = models.CharField(max_length=10, blank=True) dropoff_latitude = models.CharField(max_length=25, blank=True) dropoff_longitude = models.CharField(max_length=25, blank=True) def get_coordinates(address): .... return response['results'][0]['geometry']['location'] def save(self, *args, **kwargs): address = str(self) location = get_coordinates(address) self.dropoff_latitude = location['lat'] self.dropoff_longitude = location['lng'] super(DropoffLocationPage, self).save() def __str__(self): return (self.dropoff_address + " " + self.dropoff_city + ", " + self.dropoff_state + " " + self.dropoff_zip + " " + self.dropoff_unit_number) @register_setting class GoogleAPISetting(BaseSetting): maps_api_key = models.CharField( max_length=255, help_text="Your Google Maps API Key" ) -
How to extend query table for reviews of people I follow with user details
I'm trying to create a Django project, and currently I have three models in use: the standard Django User, Review and Follow, given below: class Review(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) text_content = models.TextField(max_length=300) movie_rating = models.IntegerField() class Follow(models.Model): following = models.ForeignKey(User, on_delete=models.CASCADE, related_name="following") follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower") What I want to get as a result is given user as a input, get all the reviews of people I follow. I used the following command Review.objects.filter(author__following__follower=user), and it gives me the user_id, text_content and movie_rating, but I'm not sure how to extend this table to add some things from the User model, such as first_name and last_name. -
How to set mode in AES using Django?
I created g-suite signup using Django it's yesterday working fine. but today I will check it throwing error(TypeError: new() missing 1 required positional argument: 'mode'). How to fix this issue. I tried many ways. but it's not working. a.py class rftoken token=models.chearfield() def pad(key): return key+ (BLOCK_SIZE - len(key) % BLOCK_SIZE) * PADDING def aes(self): p = AES.new(settings.COOKIE_SALT) return base64.b64encode(p.encrypt(rftoken.pad(str(self.id)))).decode() if rft: redirect.set_cookie('rtok', rtok.aes(), max_age=10 * 10 * 20 * 200) return redirect When I run the g-suite login code it's throwing this error Error TypeError: new() missing 1 required positional argument: 'mode' -
Celery fails to start using systemd
I am trying to daemonize my celery/redis workers on Ubuntu 18.04 and I get this error message: (archive) mark@t-rex:~/python-projects/archive$ sudo systemctl status celery ● celery.service - Celery Service Loaded: loaded (/etc/systemd/system/celery.service; enabled; vendor preset: enabled) Active: inactive (dead) (archive) mark@t-rex:~/python-projects/archive$ sudo systemctl start celery Job for celery.service failed because the control process exited with error code. See "systemctl status celery.service" and "journalctl -xe" for details. (archive) mark@t-rex:~/python-projects/archive$ journalctl -xe -- Subject: Process /bin/sh could not be executed -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- The process /bin/sh could not be executed and failed. -- -- The error number returned by this process is 3. Dec 17 10:24:39 t-rex systemd[1]: celery.service: Control process exited, code=exited status=217 Dec 17 10:24:39 t-rex systemd[1]: celery.service: Failed with result 'exit-code'. Dec 17 10:24:39 t-rex systemd[1]: Failed to start Celery Service. -- Subject: Unit celery.service has failed -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- Unit celery.service has failed. -- -- The result is RESULT. Dec 17 10:24:39 t-rex systemd[1]: celery.service: Service hold-off time over, scheduling restart. Dec 17 10:24:39 t-rex systemd[1]: celery.service: Scheduled restart job, restart counter is at 5. -- Subject: Automatic restarting of a unit has been scheduled -- Defined-By: systemd -- … -
How can I optimize the speed of this algorithm? Django and Javascript
I am new to Javascript and have decent experience with Django. I built a charting platform for my company to track metrics -- it started as a hobby project to learn Javascript but evolved into something more. The site loads and displays data correctly, but it is unbelievably slow on mobile. All of the calculations are being done on the client-side is JS. There are a lot of metrics to calculate, so the thought process was "Send the client all the Django queries in Object format, and process them there in order to not slow down the server." I also did not want to have a huge block of code processing each metric on the server (am I wrong to do this?). Some questions here: In general, where should I process the data, server-side or client-side? How can I optimize this code? I run 3 queries, and I need to find the number of hits for each metric on every day (page views, opt-ins, and scheduled calls). For example, I want to display a chart showing the number of page views over a month period with the x-axis being the date, and the y-axis being count. In order to do … -
Sending message and notification using Django channels
I am trying to implement a messaging system with live notification so that when a user is chatting with userA and userB messages the user it will update the chat messages live and it will update the user's contact list. I have two consumers, one is ChatConsumer, and another one is the UserChatNotificationConsumer which the latter is a connection for each user and server to a notification to them. And every user channel has a unique id (channel name). inside my ChatConsumer, I have a new_message() function which sends a new message from one user to another user in a private chat. After creating a message object in the new_message() function, I have two methods one which sends the message and another which sends the notification: def new_message(self, data): #create the message and other stuff. await self.send_chat_message_notification_user2(content) await self.send_chat_message(content) And my method for sending a notification to user is: async def send_chat_message_notification_user2(self, message): layer = get_channel_layer() await selg.channel_layer.group_send( self.user2_notification_layer, { 'type':'chat_message', 'message':message } ) Which self.user2_notification_layer is a string id of the second user in the chat notification channel. My issue is that the sockets are being connected successfully and I can see the CONNECT and HANDSHAKE process. however, after … -
need help using django-include-by-ajax
so i tried to use django-include-by-ajax to load the page's main content first and then load the sidebar and navigation stuff when it's ready. i followed the instructions here: https://github.com/archatas/django-include-by-ajax but it didn't work, the page dosen't load until everything is ready (which takes some time because of multiple APIs) and the side bar dosen't even work template: {% extends 'base.html' %} {% load static %} {% load include_by_ajax_tags %} {% block content %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="{% static 'app_name\css\style.css' %}"> {% include_by_ajax "app_name/templates/sidebar.html" %} <div id="content" class="p-4 p-md-5 pt-5"> <div class="row"> <div class="col-1" id="col1"> <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item"> {% if pages.has_previous %} <a class="page-link" href="?page={{ pages.next_page_number }}" aria-label="Next"> <span aria-hidden="true"><img src="{% static 'app_name/images/back.png' %}" width="50" height="50"></span></a> {% endif %} </li> </ul> </nav> </div> <div class="col-1" id="col2"> {% for url in urllist %} <img src='{{ url }}' width="800" height="800"/> {% endfor %} </div> <div class="col-1" id="col3"> <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item"> {% if pages.has_next %} <a class="page-link" href="?page={{ pages.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true"><img src="{% static 'app_name/images/forward.png' %}" width="50" height="50"></span></a> {% endif %} </li> </ul> </nav> </div> </div> </div> <script src="{% static … -
Django - "Foreign key constraint is incorrectly formed"
I'm trying to add a new model to my database, but every time i create it, i get the following error: "Foreign key constraint is incorrectly formed" This happens both if i try from MySQL and Django. Here are my models: class MainApiKeys(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) key_name = models.CharField(max_length=20) public_key = models.CharField(max_length=100, blank=True, null=True) secret = models.CharField(max_length=100, blank=True, null=True) def save(self): # ALL the signature super(MainApiKeys, self).save() class Selected_key(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) used = models.ForeignKey(MainApiKeys, on_delete=models.DO_NOTHING) def save(self): # ALL the signature super(Selected_key, self).save() If i create the same table from MySQL i'll still get the error CREATE TABLE main_selected_key( user_id INT NOT NULL, used INT NOT NULL, FOREIGN KEY (user_id) REFERENCES auth_user(id) ON DELETE CASCADE, FOREIGN KEY (used) REFERENCES main_api_keys(id) ON DELETE CASCADE) The problem is not with the Foreign Key to User, i'm sure it's the second second key because if i remove that one my code will run just fine. What am i doing wrong here? -
Error django " MultiValueDictKeyError at /employeeUpdate/ 'id' " affter I edit data
Error django " MultiValueDictKeyError at /employeeUpdate/ 'id' " affter I edit data. Here my code in views.py def employeeUpdate(request): id = request.POST['id'] emp_username = request.POST['emp_username'] emp_password = request.POST['emp_password'] emp_identification_code = request.POST['emp_identification_code'] content = employee.objects.get(pk = id) content.emp_username = emp_username content.emp_password = emp_password content.emp_identification_code = emp_identification_code if(employee.objects.filter(emp_username=emp_username)): messages.success(request, 'Username already exists') return redirect("/employeeUpdate") elif(employee.objects.filter(emp_identification_code=emp_identification_code)): messages.success(request, 'Identification already exists') return redirect("/employeeUpdate") else: content.save() messages.success(request, 'Update already !!!') return redirect("/employeeBoard")