Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn seems to slow down response time by ~30x
I have a Django app. It uses Nginx, sits on an EC2 instance, and uses an AWS load balancer in front of that. Nginx serves static files right from disk as well as using proxy_pass for everything else to route to the WSGI app server. It is the choice of WSGI server that I'm seeing puzzling results for. When I use Django's development server, ./manage.py runserver 0.0.0.0:8000, the average response time for the resulting HTML document at / is 60-70 ms: Blocked: 1 ms DNS resolution: 0 ms Connecting: 0 ms TLS setup: 0 ms Sending: 0 ms Waiting: 68 ms Receiving: 0 ms Now when I replace this with a "proper" Gunicorn server, the average response time for the same request/doc is now 1800 ms! Blocked: 1 ms DNS resolution: 0 ms Connecting: 0 ms TLS setup: 0 ms Sending: 0 ms Waiting: 1859 ms Receiving: 0 ms Here I'm running Gunicorn as: gunicorn \ --log-level DEBUG \ --bind 0.0.0.0:8000 \ --workers 4 \ project.wsgi And, notably, the response time does not change regardless of whether the number of workers is much higher e.g. --workers 64 (nor would I expect it to, since this is not about concurrent requests). … -
Django - Saving SNS Notifications
I need to receive a notification every time an object is saved in my S3 Bucket. According to the S3 documentation it is possible to enable event notifications in the bucket when an object is created in S3. SNS is one of the options. I'm looking at the AWS documentation and see that SNS can be used for: http – delivery of JSON-encoded message via HTTP POST https – delivery of JSON-encoded message via HTTPS POST That tells me that I should be able to get this notifications in my Django app using POST and I should be able to save the notifications once I receive them. However, I'm confused as to what the endpoint is. SNS requires an endpoint to send notifications to. I'm in development and my app is not in an EC2 instance yet, so I don't think I have and endpoint? Can someone provide some guidance into how I can save SNS notifications in my Django app? I saw this package but it doesn't specify what the SNS endpoint should be. -
Model field to automatically store total club members
I am building an app for a charity club that has many different users each belonging to a single club. I want to automatically increment the 'total_members' field of the class 'Club_Chapter' each time a user registers their account for a particular school (hence the User foreign key 'chapter'). models.py class Club_Chapter(models.Model): club_id = models.IntegerField(primary_key=True) school_name = models.CharField(max_length=30) state = models.CharField(max_length=4) total_members = models.IntegerField(null = False, default = 0) def __str__(self): return self.school_name # User Model class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' chapter = models.ForeignKey('Club_Chapter',on_delete=models.PROTECT) ranking = models.CharField(default='member', max_length=20) REQUIRED_FIELDS = [] objects = UserManager() forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=True) last_name = forms.CharField(max_length=30, required=True) email = forms.EmailField(max_length=254, required=True) chapter = models.ForeignKey('Club_Chapter',on_delete=models.PROTECT) password2 = None # below is my failed attempt to solve this problem Club_Chapter.objects.update(total_members=F('total_members') + 1) class Meta: model = User fields = ('first_name', 'last_name', 'chapter','email', 'password1',) I know this seams like a trivial problem but I have been searching everywhere with no luck. Any input will be greatly appreciated for the solution to this problem will help greatly with other aspects of this project. -
Django: How to pass a primary key from one view to another view?
I am using django and django-paypal for my hotel reservation system to accept payments. I am having problems with sending a primary key from one view which has the app_name system to another view in a different app called payments. I will now explain what I want to happen here: The Primary key of the room is retrieved when the user clicks on the room (reserve function) The user will press reserve, this will call the confirm function which will check if the room is available in the reservation database. (confirm function) Display a message to the user saying that the room can be reserved and automatically redirect the user to go to the process function. Process function uses paypal to allow the user to pay the price of that room.(process_payments functions) The user pays for the room via paypal and that's it Happy days!! However, I am having a problem from step 3 to step 4 because I get the this error: Reverse for 'process' with arguments '('',)' not found. 1 pattern(s) tried: ['payments/(?P[0-9]+)/process/$']. When I remove the pk from the parameters of the function and the url it works but I won't be able to charge the user … -
Django, change view from PK to slug
in my case im using a combination between PK and slug in the url. In my models, I have connect to some databases to one main database class Memories(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='remember_user') timestamp = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=200, null=True, blank=True) status = models.CharField(max_length=1, choices=STATUS, default=DRAFT) image = models.ImageField(_('Image'), upload_to=upload_to, default=False) def clean(self): if not self.is_natural: raise ValidationError('Please confirm, this is natural person and not victiv') class Meta: ordering = ["-timestamp"] verbose_name = _("Question") verbose_name_plural = _("Questions") def save(self, *args, **kwargs): if self.slug: # edit #self.title = slugify(f"{self.firstname}-{self.lastname}", to_lower=True, max_length=80) if slugify(self.firstname+"-"+self.lastname) != self.slug: self.slug = generate_unique_slug(Memories, self.firstname+"-"+self.lastname) else: # create self.slug = generate_unique_slug(Memories, self.firstname+"-"+self.lastname) super(Memories, self).save(*args, **kwargs) def __str__(self): return self.id class Content(models.Model): question = models.ForeignKey(Memories, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='remember_content_user') content = MarkdownxField() uuid_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["-timestamp"] verbose_name = _("Content") verbose_name_plural = _("Content") def __str__(self): return self.content def get_markdown(self): return markdownify(self.content) In my URLs, at this moment is based on PK urlpatterns = [ url(r'^$', views.MemoriesIndexListView.as_view(), name='index'), url(r'^add-memories/$', views.CreateMemoriesView.as_view(), name='add_memories'), url(r'^(?P<slug>[-\w]+)/$', views.MemoriesDetailView.as_view(), name='detail'), url(r'^add-content/(?P<question_id>\d+)/$', views.CreateContentView.as_view(), name='add_content'), ] And on the end, the view class CreateMemoriesView(LoginRequiredMixin, CreateView): form_class = MemoriesForm template_name = "remember/memories_form.html" message = _("saved") def form_valid(self, … -
Using windows authentication for a Django app served by linux box
I have Windows users that access a Django app that runs on a linux server. The question was asked, can that Django app use windows authentication to verify users? Or is it impossible since Django runs on a linux server. -
How to cross-check data stored in separate models?
I'm fairly new to python. I'm making a form that has a few fields from my model. The first field of this model, called EmployeeWorkAreaLog is Employee#/adp number, which is just a regular ID#. I have another model, called Salesman that is used as the main database with all the employees, and has each person's info, along with their employee #. What I was trying to achieve is that the form doesn't submit if the employee # is not valid, meaning is not currently in Salesman model. Below is what I tried to do, but I noticed that this is tying the Employee # to the auto-generated ID in the database, not the adp_number. I tried to make some changes with how the relation is but every time I ended up having to modify the Salesman model, which I cannot do, because it said something about the field being unique. Note that, in my EmployeeWorkAreaLog, the same employee can have multiple entries, so I don't know if that's what might be causing this. How could I approach this without changing Salesman? And, secondary question, not as crucial, is there any way that, upon submission, I can copy the slsmn_name from … -
Could not unpickle django-rq job
Ive setup a system for long running processes using django-rq. My worker seems fine and it says that the job runs ok: rq_1 | 19:29:24 default: league.jobs.sync_league(league_id=492233) (43c98835-7a6f-42b8-ba58-c9253781786f) rq_1 | 19:29:24 default: Job OK (43c98835-7a6f-42b8-ba58-c9253781786f) But my data from the job does not show up in the system and when clicking on finished jobs i get the message: ('Could not unpickle', UnpicklingError('pickle data was truncated')) The view that enques the job looks like this: from .jobs import sync_league django_rq.enqueue(sync_league, league_id=league_id) And the job itself, a bit shortened: async def sync_league(league_id): async with aiohttp.ClientSession() as session: #more code.... for team in page_results: team = Team.objects.get_or_create( name=team["entry_name"], fpl_id=team["entry"] ) team.save() league.teams.add(team) league.sync_team_standings() Ive also tried changing the job to only print("test") but that gives the same pickling error. -
How to fix missing values in id field after adding and removing primary key in django model?
I added a primary key for a model but then ran into some downstream problems because the automatically generated id field was gone. Now, I removed that key again, but the id column was deleted apparently and I guess all the values are gone. So, setting a default value does not really make sense because other models need to know the old values. How can I fix that? Currently, I still get the error when I try to migrate: django.db.utils.ProgrammingError: column "id" of relation "pipeline_file" does not exist -
How to override empty_label in filter django based in SimpleListFilter?
I'm making a filter on django based on SimpleListFilter, I would like to know if there is a way to replace the label all in the filter. I tried ovveride empty string but not works class IgnoreAttendanceReportFilter(admin.SimpleListFilter): title = 'Aulas ignoradas pelo extrato de frequência' parameter_name = 'aula__status__ignore_in_attendance_report' def lookups(self, request, model_admin): return ( ('yes', 'Sim'), ('', 'No'), ) def queryset(self, request, queryset): if self.value() == 'yes': return queryset.filter(aula__status__ignore_in_attendance_report=True) # return queryset return queryset.filter(aula__status__ignore_in_attendance_report=False) This way in my display list: all, Yes and No, I want to change all for No, this way default filter is will be No, and my display only Yes and No. -
how to setup x server & set display key stroke events from pynput on AWS ec2
m able to get the keystroke event on my local system when using pynput package. But it doesn't work same on AWS EC2 instance giving error Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/Xlib/support/unix_connect.py", line 119, in get_socket s = _get_unix_socket(address) File "/usr/local/lib/python3.7/site-packages/Xlib/support/unix_connect.py", line 98, in _get_unix_socket s.connect(address) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/Xlib/support/unix_connect.py", line 123, in get_socket s = _get_tcp_socket(host, dno) File "/usr/local/lib/python3.7/site-packages/Xlib/support/unix_connect.py", line 93, in _get_tcp_socket s.connect((host, 6000 + dno)) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./demo.py", line 10, in import pynput File "/usr/local/lib/python3.7/site-packages/pynput/init.py", line 40, in from . import keyboard File "/usr/local/lib/python3.7/site-packages/pynput/keyboard/init.py", line 49, in from ._xorg import KeyCode, Key, Controller, Listener File "/usr/local/lib/python3.7/site-packages/pynput/keyboard/_xorg.py", line 39, in from pynput._util.xorg import ( File "/usr/local/lib/python3.7/site-packages/pynput/_util/xorg.py", line 40, in _check() File "/usr/local/lib/python3.7/site-packages/pynput/_util/xorg.py", line 38, in _check display = Xlib.display.Display() File "/usr/local/lib/python3.7/site-packages/Xlib/display.py", line 89, in init self.display = _BaseDisplay(display) File "/usr/local/lib/python3.7/site-packages/Xlib/display.py", line 71, in init protocol_display.Display.init(self, *args, **keys) File "/usr/local/lib/python3.7/site-packages/Xlib/protocol/display.py", line 89, in init self.socket = connect.get_socket(name, protocol, host, displayno) File "/usr/local/lib/python3.7/site-packages/Xlib/support/connect.py", line 87, in get_socket return mod.get_socket(dname, protocol, host, dno) File "/usr/local/lib/python3.7/site-packages/Xlib/support/unix_connect.py", … -
Django/Postgres ORM Model
I have this done in other languages but currently beating my head on the table in this one. The goal of what I am doing is that data is not deleted (ever) just masked by a newer record for history logging. Before anyone asks, this is a requirement not an option. The three fields look like follows: | id | row_id | update_id | |------|--------|-----------| | uuid | uuid | uuid | The concept of this is for a single record the id will never change throughout the history of that record and will be used as the official reference of that record. The row_id is the primary key and and always exists The update_id is null for the latest update of the record and in the history it always is updated to the record row_id that replaced it. There are other fields to these tables but they aren't relevant to what I am trying to accomplish. import uuid from django.db import models class MyObject(models.Model): id = models.UUIDField( auto_created=True, default=uuid.uuid4, editable=False, null=False, ) row_id = models.UUIDField( auto_created=True, default=uuid.uuid4, editable=False, primary_key=True, null=False, unique=True, ) update_id = models.UUIDField( editable=False, unique=True, ) Now I gather that the MyObject.save() will insert or update the … -
How i fix this Unable to import 'django.urls' error?
Errors are: 1. No name 'urls' in module 'django'pylint(no-name-in-module) Unable to import 'django.urls' 2. No name 'test' in module 'django'pylint(no-name-in-module) Unable to import 'django.test'pylint(import-error) 3. No name 'http' in module 'django'pylint(no-name-in-module) Unable to import 'django.http'pylint(import-error) When I start the server the terminal shows me this - Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\aviba\appdata\local\programs\python\python38-32\Lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\aviba\appdata\local\programs\python\python38-32\Lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\aviba\Envs\test\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\aviba\Envs\test\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\aviba\Envs\test\lib\site-packages\django\core\management\base.py", line 387, in check all_issues = self._run_checks( File "C:\Users\aviba\Envs\test\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\aviba\Envs\test\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\aviba\Envs\test\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\aviba\Envs\test\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\aviba\Envs\test\lib\site-packages\django\urls\resolvers.py", line 399, in check for pattern in self.url_patterns: File "C:\Users\aviba\Envs\test\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\aviba\Envs\test\lib\site-packages\django\urls\resolvers.py", line 584, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\aviba\Envs\test\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\aviba\Envs\test\lib\site-packages\django\urls\resolvers.py", line 577, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\aviba\Envs\test\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", … -
Django Download third party video instead of opening in new/same tab
I am currently trying to make a user download a video on clicking a link . But everytime on clicking the URL(href) it opens it a new tab. The video URL is a third-party URL(Instagram CDN). Here is my code snippet in my template.html for the page . padding: 20px 0px;color: rgb(38, 38, 38); font-size: 16px; font-weight: 500; transition: all 0.2s ease 0s;" download>DOWNLOAD</a> ``` I intentionally added '&amp;dl=1' to the URL part hoping it might make some impact but to no avail. Removing/Adding the attribute 'download' seems to have no impact. What should I do to force download it and not open in new tab. -
Django and Javascript to pass a variable to another page
I am trying to build a chatroom using Django and Django Channels. What I would like to do is set an input element to accept a user alias and then carry that username into the chatroom. I am not using a data model and would like to pass this variable from the chatroom select page to the chatroom just using JavaScript without utilizing the URL to Post username data. I do not want to use the User module in Django because I don't want to require authentication, just allow the user to set a name. Here is the code I am currently using, I know it is not syntactically correct, but should give an idea of what I am trying to do. I will asterisk the sections that break the code. The HTML: <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Rooms</title> </head> <body> *Enter an alias:<br> *<input id="username-name-input" type="text" size="100"/><br/> Enter a chatroom name:<br/> <input id="room-name-input" type="text" size="100"/><br/> <input id="room-name-submit" type="button" value="Enter"/> <script> document.querySelector('#room-name-input').focus(); document.querySelector('#room-name-input').onkeyup = function(e) { if (e.keyCode === 13) { // enter, return document.querySelector('#room-name-submit').click(); } }; document.querySelector('#room-name-submit').onclick = function(e) { var roomName = document.querySelector('#room-name-input').value; *var userName = document.querySelector('#username-name-input').value; window.location.pathname = '/' + roomName + '/'; }; </script> … -
Display block datatable - django-tables2
I am using django-tables2 and i want to display my data of table in block form. Just like in this question. I know how the css would be changed and how the html file would be called but i am unable to handle custom css which would display current the table format into block format. Undermentioned is the code which i am trying to alter. It is django_tables2/bootstrap4.html of django-tables2 {% block table.tbody %} {# <tbody {{ table.attrs.tbody.as_html }}>#} {% for row in table.paginated_rows %} {% block table.tbody.row %} <tr {{ row }}> {% for column, cell in row.items %} <td {{ column.attrs.cell }}>{% if column.localize == None %}{{ cell }}{% else %}{% if column.localize %}{{ cell|localize }}{% else %}{{ cell|unlocalize }}{% endif %}{% endif %}</td> {% endfor %} </tr> {% endblock table.tbody.row %} {% empty %} {% if table.empty_text %} {% block table.tbody.empty_text %} <tr><td colspan="{{ table.columns|length }}">{{ table.empty_text }}</td></tr> {% endblock table.tbody.empty_text %} {% endif %} {% endfor %} </tbody> {% endblock table.tbody %} -
Why do static files won't load in the web app?
So I've seen a lot of tutorials here explaining what to do, but no matter what I change the static files won't seem to load. This is what my files are looking like atm settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(PROJECT_ROOT, "static"),''] job_app/urls.py urlpatterns = [ path('', main, name='index'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) index.html <!DOCTYPE html> <html lang="en"> <head> <title>JobPortal - Free Bootstrap 4 Template by Colorlib</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> {% load static %} <link href="https://fonts.googleapis.com/css?family=Nunito+Sans:200,300,400,600,700,800,900" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/open-iconic-bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/animate.css' %}"> <link rel="stylesheet" href="{% static 'css/owl.carousel.min.css' %}"> <link rel="stylesheet" href="{% static 'css/owl.theme.default.min.css' %}"> <link rel="stylesheet" href="{% static 'css/magnific-popup.css' %}"> <link rel="stylesheet" href="{% static 'css/aos.css' %}"> <link rel="stylesheet" href="{% static 'css/ionicons.min.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap-datepicker.css' %}"> <link rel="stylesheet" href="{% static 'css/jquery.timepicker.css' %}"> <link rel="stylesheet" href="{% static 'css/flaticon.css' %}"> <link rel="stylesheet" href="{% static 'css/icomoon.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> jobber/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('job_app.urls')) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
How django template url matching works
I'm trying to figure out how url matching works in django template. What i'm trying to achieve is when clicking on a link it would bring up a specific objects. Models.py class PostManager(models.Manager): def get_queryset(self): return super(PostManager,self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = (('published','Published'), ('draft','Draft ')) FIELD_CHOICES = (('1','1 Title and body field'), ('2','2 Title and body fields'), ('3','3 Title and body fields'), ('4', '4 Title and body fields'), ('5', '5 Title and body fields')) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post') title = models.CharField(max_length=100) sub_title = models.TextField(max_length=50,default="") title_1 = models.CharField(max_length=100,null=True,blank=True) title_1_body = models.TextField(null=True,blank=True) title_2 = models.CharField(max_length=100,null=True,blank=True) title_2_body = models.TextField(null=True,blank=True) title_3 = models.CharField(max_length=100,null=True,blank=True) title_3_body = models.TextField(null=True,blank=True) title_4 = models.CharField(max_length=100,null=True,blank=True) title_4_body = models.TextField(null=True,blank=True) title_5 = models.CharField(max_length=100,null=True,blank=True) title_5_body = models.TextField(null=True,blank=True) created = models.DateField() publish = models.DateTimeField(default=timezone.now) slug = models.SlugField(max_length=250, unique_for_date='created') status = models.CharField(max_length=250, choices=STATUS_CHOICES, default='draft') object = models.Manager() postManager = PostManager() class Meta(): ordering = ('publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[self.slug]) def get_image_filename(instance, filename): title = Post.title slug = slugify(title) return "media/%s-%s" % (slug, filename) class Image(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='images') image_1 = models.ImageField(upload_to=get_image_filename,default='123.jpg',verbose_name="Image",null=True) image_2 = models.ImageField(upload_to=get_image_filename,default='123.jpg',verbose_name="Image",null=True) image_3 = models.ImageField(upload_to=get_image_filename,default='123.jpg',verbose_name="Image",null=True) image_4 = models.ImageField(upload_to=get_image_filename,default='123.jpg',verbose_name="Image",null=True) image_5 = models.ImageField(upload_to=get_image_filename,default='123.jpg',verbose_name="Image",null=True) views.py def post_detail(request): post = get_object_or_404(Post) return render(request, 'blog_application/templates/single.html', {'post':post}) index.html {% for elem in … -
Is It Possible To Have A Theme Selector For Users To Choose The Style of Their Site?
I was wondering if it's possible to have a option for users to pick from a set of themes/styles they want for there site like wordpress or forums? I plan on releasing a script for people to use but I don't want them to all have the same theme so I would like to have a option for them to select one they like that I created or have them be able to upload/create there own from the admin cp Thanks anyone for the help! -
UNIQUE constraint failed on adding a new model field in django
When i want to add a new field called slug to my Post model in Djnago, the migrate command will raise UNIQUE constraint failed: new__chat_post.slug After that i remove that field from my model but the problem still exists. why?? and how to resolve this problem without deleting my whole table data?? The database is sqlite3 and the Django version is 2.2 . thanks. The model: class Post(models.Model): title = models.TextField(max_length=100) context = models.TextField(max_length=255) creation_date = models.DateTimeField(default = timezone.now) author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete = models.CASCADE) slug = models.SlugField(default=["title"],unique=True) -
Django Template Passing form input to url
I am trying to add form input data in url. this is my current template where I pass the parameter smith hardcoded: <input type="text" placeholder="Search.." name="name"> <a href="{% url 'data' name='smith' %}">Search</a> I don't pass the parameter dynamically, I mean, input data will be parameter like name=inputdata How can I do it? Can anyone help me? -
How to properly use FieldKeys to verify data in separate models?
I'm making a form that has a few fields in my model. The first field of this model, called EmployeeWorkAreaLog is Employee#/adp number. I have another model, called Salesman that is used as the main database with all the employees, and has each person's info, along with their employee #. What I was trying to achieve is that the form doesn't submit if the employee # is not valid, meaning is not currently in Salesman model. Below is what I tried to do, but I noticed that this is tying the Employee # to the auto-generated ID in the database, not the adp_number. I tried to make some changes with how the relation is but every time I ended up having to modify the Salesman model, which I cannot do, because it said something about the field being unique. Note that, in my EmployeeWorkAreaLog, the same employee can have multiple entries, so I don't know if that's what might be causing this. How could I approach this without changing Salesman? And, secondary question, not as crucial, is there any way that, upon submission, I can copy the slsmn_name from Salesman into the corresponding employee_name? I had created the get_employee_name() function, … -
upgrading Django and Python versions, problem with default value for FloatField set to string
In a model using Django 1.8 and Python 2.7 we had a migration that accidentally set the default value for a FloatField to an empty string (default=''), which Django appears to have interpreted as a bytes-string: class Migration(migrations.Migration): dependencies = [ ('reo', '0030_merge'), ] operations = [ migrations.CreateModel( name='ProfileModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('pre_setup_scenario_seconds', models.FloatField(default=b'', null=True)), ], ), ] After upgading to Django 2.2 and Python 3.6, Django gives the warning with manage.py migrate that there are un-migrated changes. After changing the default value from '' to None and running manage.py makemigrations we get: operations = [ migrations.AlterField( model_name='profilemodel', name='pre_setup_scenario_seconds', field=models.FloatField(default=None, null=True), ), ] Then running manage.py migrate yields: nlaws-> python manage.py migrate Operations to perform: Apply all migrations: auth, contenttypes, django_celery_results, proforma, reo, resilience_stats, sessions, summary, tastypie Running migrations: Applying reo.0050_auto_20191030_1738...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/nlaws/.virtualenv/api/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/nlaws/.virtualenv/api/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/nlaws/.virtualenv/api/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/nlaws/.virtualenv/api/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/nlaws/.virtualenv/api/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/nlaws/.virtualenv/api/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/Users/nlaws/.virtualenv/api/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate … -
"The value of 'list_display[1]' refers to 'discount', which is not a callable, an attribute of 'OfferAdmin'
when i run server i am facing error : : (admin.E108) The value of 'list_display[1]' refers to 'discount', which is not a callable, an attribute of 'OfferAdmin', or an attribute or method on 'products.Offer'. I tried following piece of code in a file named admin.py from django.contrib import admin from .models import Product, Offer class OfferAdmin(admin.ModelAdmin): list_display = ('code', 'discount') class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'price', 'stock') admin.site.register(Offer, OfferAdmin) admin.site.register(Product, ProductAdmin) before adding class OfferAdmin code was working fine. However after adding it. this is showing error I'm using django version 2.1.5 -
Django request timeout for some static files when running manage.py test package.to.unit.test
Context: We run Cypress tests which use instances of our application started using manage.py test package.test.suite. The test fixtures and environment are all set up using a class extended from django.contrib.staticfiles.testing.StaticLiveServerTestCase. A unit test/method is added to the extended class which invokes Cypress as a subprocess to run the tests and asserts against the exit code of the subprocess. Versions: Python: 3.6.8 Django: 2.2.3 macOS: Mojave 10.14.6 The problem: This worked well until yesterday when I updated Cypress via npm. Now when I start a server using manage.py test some.test.suite the server will fail to serve all of the static resources requested by the browser. Specifically, it almost always fails to serve some .woff fonts and a random javascript file or two. The rest of the files are served but those 5 or 6 which the browser never receives a response for. Eventually I'll get a ConnectionResetError: [Errno 54] Connection reset by peer error (stack trace below) in the terminal. Additionally, if I enable the cache in my browser and attempt a few refreshes things will work fine, almost as if theres a limit to the number of files that can be served at once and once some files are …