Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2 CreateView HTML add link next to a field HTML
I am using a Create View in Django 2 in order for the user to input data into the database. Nothing fancy. All I want to do is add an anchor tag next to one of the fields that links out to a help page on that specific field. Is there a simple way to do this using HTML or CSS? For example, if I have a Student Model with a Boolean field asking if a student is eligible for the honor society. I want to link out to a page that discusses eligibility requirements. I have included an example of what my create-view HTML pages look like for reference. <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" class='btn btn-primary' value="Submit"> </form> Is this possible without creating a form from scratch? All help appreciated. -
How to use Django's HTML form to edit a part of users profile.
I have a user profile model I use django model forms to create and edit the users profiles Now I want to change only 2 fields on the profiles lat and lon . So on my Index.html I have a small html form . As soon as the user clicks locate me. The latitude and longitude are automatically filed in and the submit button will be clicked using Jquery. How do I use the details from this form to update my users lat and lon. Its just that I have not used django's HTML form's and I need to update the lat lon entered on this mini form to the users profile <form method="post" action="{{ ??????????? }}"> <input id="jsLat" type="text" placeholder="latittude" > <input id="jsLon" type="text" placeholder="longitude"> <button type="submit" id="submit">Submit</button> </form> Do I create another view & url (that way I will have 2 profile edit views and 2 profile edit url's) to add the lat and lon to my existing profile. Or Is there a way I can use the existing view and url and update the 2 fields below are my models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=100) age = models.DateField(blank=True, null=True) profile_image = models.ImageField(default='', blank=True, … -
Django ManyToManyField not saving in joint table
I have a model defined like so: class Vote(models.Model): text = models.CharField(max_length=300) voters = models.ManyToManyField(CustomUser, blank=True) game = models.ForeignKey(Game, on_delete=models.CASCADE) I want a vote to automatically add all players of its associated game to its list of voters, when it is created. The Game model has a method that returns its players, so I have overridden the save method of the Vote model: def save(self, *args, **kwargs): super().save(*args, **kwargs) #As the docs state it must be saved before m2m elements can be added queryset = self.game.get_players for player in queryset: self.voters.add(player.id) This does not work. It does not throw an error, and happily saves the model instance through the admin site. It does not, however, seem to add any of the players to the voters field, (and the vote_voters table remains empty in the db). Obvious troubleshooting: the queryset is definitely not empty, the save method is definitely being called. -
modify request.query_params in django
I want to modify request.query_params from the django view, to add new parameters I send a request / api / users /? search = users from my view I get request.query_params which returns a querydict, well what I want is to add search = users to request.query_params but from my view, any ideas? -
Is there a standard way to store test coverage results to compare them in time?
I have a Django project in which I can run coverage and create the report coverage run --source='.' manage.py test my_app I would like to compare the results over time after code refactors. Is there a way to achieve this without creating my own data model? Thanks in advance, -
AWS Load Balancing two instances. One has crashed. Should I duplicate the working one?
So what had happened, lucky for us, is that one of our instances has crashed. The second one runs perfectly as they are both attached to a load balancer for AWS EC2 instances. Because this is a sensitive server I wanted to pass by what I had in mind to do for some advice. First, I am thinking about removing the broken instance (instance6) from the load balancer. After doing so I was going to create another instance with the image of the working one (instance5) along with the same security group. Followed by django, nginx and uwsgi installation and a clone. Finally, python manage.py runserver and the usual server set up. Ideally, instance5 is working perfectly and I would like for instance6 to work the same way. I have done some reading but feeling not as confident as I hope to be. The developer that works with our instances has left and many of us are not 100% on everything. EDIT: Am I better off trying to fix instance6? Im trying everything I can with it but the supervisord is not working the same even though the conf files are both similar. -
Django, Social Auth App Facebook "502 Bad Gateway" after click login button
HELP! I'm using Django and Social Auth App Facebook, after click "login button", it gives me "502 Bad Gateway" error, i can't login. Live project: https://nicknhanh.com https://i.stack.imgur.com/b86tr.png https://i.stack.imgur.com/hgAcE.png -
How can I used adsense in my django templates for changing
I will use adsense in my site. For instance; I have base.html, post_list.html and post_detail.html. I will use adsense block in base.html. İf user enter a post detail button in post_list page and if we go to the post detail page, does the ad change. Imagine like that: base.html <html> <head> .... </head> <body> <nav> .... </nav> <div class="adsense"> adsense block </div> {% block content %} {% endblock content %} post.html: {% extends 'base.html' %} {% block content %} for post in post list: <a href="{% url 'post_detail' post.id">Post Detail</a> {% endblock content %} post_detail.html: {% extends 'base.html' %} {% block content %} post detail {% endblock content %} I am a new programmer in Django. I am using nested django template. I am creating social app and I need money. İt is important for me because I will use one more adsense in my site. Thanks :) urls.py in my app .... url(r"post_list/",post_list,name ="post_list"), url(r"post_detail/(?P<id>[-\w]+)/$",post_detail,name="post_detail"), -
Nginx Failed to start A high performance web server and a reverse proxy server
My entire website in ubuntu is down.When I check the status.I got: Aug 30 21:39:44 ubuntu-s-1vcpu-2gb-nyc1-01 nginx[23017]: nginx: [emerg] "worker_processes" directive invalid value in /etc/nginx/nginx.conf:2 Aug 30 21:39:44 ubuntu-s-1vcpu-2gb-nyc1-01 nginx[23017]: nginx: configuration file /etc/nginx/nginx.conf test failed Aug 30 21:39:44 ubuntu-s-1vcpu-2gb-nyc1-01 systemd[1]: nginx.service: Control process exited, code=exited status=1 Aug 30 21:39:44 ubuntu-s-1vcpu-2gb-nyc1-01 systemd[1]: Failed to start A high performance web server and a reverse proxy server. This is my /etc/nginx/nginx.conf: user www-data; worker_processes autoi; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } -
Rest Framework serializers, forbid users to change others password
I'm creating a simple web app and I cannot find any way to forbid other users from changing your password. This is minimal code: # serializers.py from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): def create(self, validated_data): # have to use custom create method because default method calls `User.objects.create()` which doesn't take care of password hashing and other important stuff return User.objects.create_user(**validated_data) class Meta: model = User fields = ('id', 'username', 'email', 'password') read_only_fields = ('id', 'username') # password is set to write_only because I don't want to send it to anybode (even though it's just a hash) extra_kwargs = {'password': {'write_only': True}} # views.py from .serializers import UserSerializer from rest_framework import generics from django.contrib.auth.models import User class UserDetails(generics.RetrieveUpdateAPIView): queryset = User.objects.all() serializer_class = UserSerializer I could take care of this myself by using APIView. # views.py from .serializers import UserSerializer from rest_framework.views import APIView from django.contrib.auth.models import User class UserDetails(APIView): def put(self, request, format=None): serialized = UserSerializer(data=request.DATA) if not serialized.is_valid(): return # probably HTTP 400 Error code if request.user.id != serialized.data['id']: # this if is what I'm trying to achieve return # probably HTTP 403 Error code user = User.objects.update( id=serialized.data['id'], email=serialized.data['email'] ) if 'password' in request.DATA: user.set_password(request.DATA['password']) return # probably … -
Manually filling disabled fields of Django ModelForm
I am facing the following scenario: I have a Django model class called Contact, which looks something like: class Contact(models.Model): first_name = models.CharField(max_length=70) last_name = models.CharField(max_length=70) company = models.ForeignKey(Company) // should be disabled in user-facing forms organizations = models.ManyToManyField(Organization) // should be disabled and hidden in user-facing forms // some other fields not relevant to this question Both users of the app and administrators should be able to create objects of type Contact and store it in the database. However, for a user this should be restricted in the way that he cannot freely chose the company field of a Contact object. For this, I have created a base ModelForm called ContactForm, intended to be used by administrators, and a restricted user-facing child class called RestrictedContactForm. The code looks as follows: class ContactForm(forms.modelForm): class Meta: model = Contact fields = ['first_name', 'last_name', 'company', 'organizations'] class RestrictedContactForm(ContactForm): class Meta(ContactForm.Meta): widgets = {'organizations': forms.HiddenInput()} def __init__(self, *args, **kwargs): super(RestrictedContactForm, self).__init__(*args, **kwargs) // Maybe populate company and organization here somehow? self.fields['company'].disabled = True self.fields['organization'].disabled = True The RestrictedContactForm is rendered to the user once he decides to create a new contact. Clearly, as both the company and organization fields are mandatory, they need … -
Log Django command output to Apache error log
How do I get log output from my custom Django commands in to the Apache logs? In settings.py, I have the logger set to log to the console, as that is the only way I've found to get the Django app to write logs to the Apache log. However, if I then use the app logger within a Django command and run that command from the command line (e.g. python manage.py my_command), the logging set up writes to the actual console instead of the Apache log. Can I configure the logging differently, or even call the Django command differently, to get the command logging to write to the Apache log? settings.py logging snippet: 'handlers' : { 'console':{ #this logs to the Apache log when called from within the Django app e.g. from within views.py 'level':'INFO', 'class':'logging.StreamHandler', 'formatter':'standard', } } .... 'loggers' : { 'app_logger': { 'handlers': ['console'], 'level':'DEBUG', } } my_command.py snippet: .... class Command(BaseCommand): .... def handle(self, *args, **options): # do some useful work here log = logging.getLogger("app_logger") # when called from the command line, this statement is logged back to the console, not the Apache log log.info("something happened") -
TypeError: document.getElementById(...) is null Django + JS
I'm having an error while executing the following code: var toppings = ['Zucchini', 'Fresh Garlic', 'Black Olives', 'Anchovies', 'Barbecue Chicken', 'Artichoke', 'Spinach', 'Ham', 'Sausage', 'Mushrooms']; var appended = 0; var maxAppended = 3; document.getElementById('add').onclick = () => { appended+=1; if(appended <= maxAppended){ const topping = document.createElement('select', { 'name': 'Topping', 'class': 'form-control' }); list.appendChild(topping); toppings.forEach(function(item, i, arr) { const ch_topping = document.createElement('option'); ch_topping.innerHTML += item; topping.appendChild(ch_topping); }); } else { alert('You should stop'); } }; page1.html: <div class="form-group" id='add_one'> <br> <h5>You can add up to 3 toppings to your pizza!</h5> <ol id="list"></ol> <button class="btn btn-primary" id="add" type="submit">Add topping</button> </div> This code fails with the following error: TypeError: document.getElementById(...) is null I'm including JavaScript on my base.html file and page1.html extends this file. My base.html <head>: <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous"> <script src="{% static 'js/main.js' %}"></script> window.onload() didn't help jQuery's $(document).ready() didn't help -
How to Create Django Object w/ Nested Images using django-rest-framework and Javascript
So I am trying to upload multiple images using JS/Paw (Client identical to Postman) to a Django API endpoint generated by django-rest-framework ("DRF"). I have looked at all of the answers on StackOverflow, but have yet to find an implementation that works for me. So far, if I add an "ad" field to my Paw multipart/form-data POST request, it simply does not show up when I print() my validated_data. I am trying to find a way to POST all of my data via Paw/JS to DRF in order to allow it to create a new instance of Campaign, as well as create multiple Ads, and associate it with the newly created campaign. Any suggestions are appreciated. views.py class UserCampaignCreate(generics.CreateAPIView): serializer_class = serializers.UserCampaignSerializer queryset = models.Campaign.objects.all() parser_classes = (MultiPartParser, FormParser) models.py class Campaign(TimeStampedModel): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='campaignAsUser') title = models.CharField(max_length=55) slug = AutoSlugField(populate_from='title', unique=True, always_update=True) description = models.CharField(max_length=255, blank=True) location = models.ManyToManyField(Location, related_name='campaignAsLocation') start_date = models.DateTimeField() end_date = models.DateTimeField() uuid = models.UUIDField(default=uuid.uuid4, editable=False) def __str__(self): return '{0}'.format(self.title) class Ad(TimeStampedModel): title = models.CharField(max_length=55, blank=False) image = models.ImageField(upload_to=PathAndUniqueFilename('ad-placement-image/')) campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, related_name='adAsCampaign') uuid = models.UUIDField(default=uuid.uuid4, editable=False) def __str__(self): return '{0}'.format(self.title) serializers.py class UserCampaignSerializer(serializers.ModelSerializer): location = LocationSerializer(many=True) class Meta: fields = ( … -
DRF nested-relationships : models relations
Assuming I have a model classes as, class Estudiante(models.Model): nombre = models.CharField(..) ... class Invitado(models.Model): invitadoi = models.ForeignKey(Estudiante) ... class Respuesta(models.Model): nombrer = models.ForeignKey(Invitado, related_name="invitado") ... How can I create a Respuesta serializer and get nombre field of Estudiante model in the json result? -
Django Sliderbar
Let me preface this by saying I have almost no coding experience and have absolutely no idea what I'm talking about. I am working on a project in django and have been asked to implement a slider bar that allows users to select an upper and lower bound from values taken from the SQL database. I have created a sliderbar using jQuery that looks how I would like (allowing a user to pick an upper and lower bound), but I have absolutely no idea how to connect this to the values stored in the SQL database or if this is even possible. Currently, a django form has been implemented that prompts the user for an lower and upper bound in the form of text boxes. A line of text with the minimum and maximum acceptable values (taken from the SQL database) is written above the text boxes. Is there any straightforward way to just have my sliderbar write the values of these textboxes and let the user submit them? Thanks to anyone who can offer me any help or tips with this. I would like to just post the code for people to look at, but this is part of … -
Insert json into postgres as part of celery task
I am new to Django and Celery. high level: I am working on a Django application. From an admin page uses will submit Requests (jobs). Those Requests will get sent to Redis. Celery will then poll Redis and pull a job from the queue. Once the task is finished the results will be stored in postgres. Here is an example task that is used to kick off some tests via pytest.main(). # task for running tests by marker def run_tests_mark(test_marker): os.chdir('/service/lib/tests') # only allow specific strings to be passed in by the user if test_marker not in ['smoke', 'regression']: # update as more tages are introduced to the project return 'You have entered an invalid term. Please use either smoke of regression.' # run pytest command with self contained reporting results = pytest.main(['-v', '--json-report', '-m', test_marker]) # TODO: after tests run send json report to postgres The code will run the tests, but as you can see by the last comment I want to take the resulting .json.report and store it in a postgres db [please note I use a helper to grab the actual report generated by results] Now here is where I get confused. Do I need to … -
Django Wizard Form and other view in one page
I'm trying to show a wizard form and a table (that is generated by this form and can be seen in every step) in one page. Is it possible? I have tried: urls.py urlpatterns = [url('', GroupsWizard.as_view(form_list), name = 'index'),] views.py def index(request): groups_render = Groups.objects.all() return render(request, 'index.html', {'groups_render' : groups_render}) class GroupsWizard(SessionWizardView): def get_template_names(self): return 'index.html' def done(self, form_list, **kwargs): data = {k: v for form in form_list for k, v in form.cleaned_data.items()} instance = Groups.objects.create(**data) return render(self.request, 'grupos/done.html', { 'form_data': [form.cleaned_data for form in form_list], }) index.html <div> {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} </div> <div> {{ groups_render }} </div> Thanks -
Django + Vue with multiple apps
There are plenty of tutorials and helpful posts how to use Django and Vue properly (in various options) all over the Internet. But I didn't find a single one who describes how to create a Django application which consists of more than one app, each having it's own part of the Vue frontend. I am creating a Django application with a Vue frontend, and it will have a lot of apps that can be plugged into the main system very easily (using a custom framework). But this only is the backend. I'd like to enable each Django app for having a "plugin" part of the frontend as well: e.g. a set of Vue components that are rendered "dynamically" in the frontend when this app is added in INSTALLED_APPS. How can I provide "plugin hooks" in Vue to load those components? All the things I have seen (dynamic/lazy component loading with webpack etc.) is not what I want. It only describes how to load a component that is predefined later in the http request timeline. How am I supposed to "merge" all the components? Can I simply create components in static folders and let ./manage.py collectstatic do the magic? Can anyone … -
405 Client Error: Method Not Allowed for url: https://rinkeby.infura.io PYTHON
I Can't call create filter on my contract, this is my code below- I am able to get the contract and run functions on it, but I cant listen to events: myContract = w3.eth.contract(address="some_address",abi=contract_abi) This is where I run into issues: myfilter_new= myContract.events.Transfer.createFilter(fromBlock=0, toBlock='latest') this is the issue I get: HTTPError at /testing/ 405 Client Error: Method Not Allowed for url: https://rinkeby.infura.io/my_api_key -
Python : Django TypeError: object() takes no parameters
I'm porting a django application from 1.x to 2.1 and got stuck with the error that says "TypeError: object() takes no parameters". I'm trying to solve the problem for quite a while but not even got a clue even after days of debugging and searching online There are no problems with the indentation, celery version : 4.2.1 raven version : 6.9.0 django version : 2.1 Here is my wsgi.py import os from raven.contrib.django.raven_compat.middleware.wsgi import Sentry from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", “settings") application=Sentry(get_wsgi_application()) Here is an excerpt from the error log File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/app/wsgi.py", line 16, in <module> application=Sentry(get_wsgi_application()) File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/wsgi.py", line 136, in __init__ self.load_middleware() File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 36, in load_middleware mw_instance = middleware(handler) TypeError: object() takes no parameters Any help would be appreciated. -
Django: How does it find the User model?
I have a question to the AUTH_USER_MODEL in Django: https://docs.djangoproject.com/en/dev/ref/settings/#auth-user-model The default value is auth.User. However, the actual model is in auth.models.User. How does Django find the correct class? I am asking because when I usually use models in Django, I have to write from myapp.models import MyModel. So, why do I not need models in auth.User for AUTH_USER_MODEL? Can some explain me that or show the code that uses it? -
Django: How does it find auth.models.User?
I have a question to the AUTH_USER_MODEL in Django: https://docs.djangoproject.com/en/dev/ref/settings/#auth-user-model The default value is auth.User. However, the actual model is in auth.models.User. How does Django find the correct class? I am asking because when I use models in Django, I have to write from myapp.models import MyModel. So, why do I not need models in that case? Can some explain me that or show the code that uses it? -
Django: get the max count of a foreign key based on other foreign key
I have this Model: class Complaint(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True) name = models.CharField(max_length=255, unique=True) definition = models.TextField(blank=False, default="") is_violent = models.BooleanField(default=False) is_active = models.BooleanField(default=True) def __str__(self): return self.name class Meta: ordering = ['name'] def get_absolute_url(self): return reverse('complaint-details', kwargs={'pk': self.pk}) class Service(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True) name = models.CharField(max_length=255, unique=True) definition = models.TextField(blank=True, default="") is_active = models.BooleanField(default=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('service-details', kwargs={'pk': self.pk}) class Location(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True) location_name = models.CharField(max_length=255, unique=True) loc_lat = models.DecimalField(max_digits=9, decimal_places=6) loc_long = models.DecimalField(max_digits=9, decimal_places=6) pop = models.PositiveIntegerField(default=500) is_AOR = models.BooleanField(default=False) is_active = models.BooleanField(default=True) def __str__(self): return self.location_name class Blotter(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True)#default=timezone.now().date() date = models.DateField(blank=True) time = models.TimeField(blank=True) entry_number = models.CharField(max_length=255, unique=True,validators=[RegexValidator(r'^\d{1,255}$')]) complaints = models.ForeignKey(Complaint, on_delete=models.CASCADE, null=True, blank=True) service = models.ForeignKey(Service, on_delete=models.CASCADE, null=True, blank=True) information = models.TextField(blank=False, default="") location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True, blank=True) is_active = models.BooleanField(default=True) class Meta: ordering = ("date_created",) def __str__(self): return (self.entry_number) def get_absolute_url(self): return reverse('details-blotter', kwargs={'pk': self.pk}) And I have this serializer: class APILocationListSerializer(serializers.Serializer): address = serializers.CharField() latitude = serializers.DecimalField(max_digits=9, decimal_places=5) longitude = serializers.DecimalField(max_digits=9, decimal_places=5) population= serializers.IntegerField() crime_count=serializers.IntegerField() crime_rate=serializers.DecimalField(max_digits=4, decimal_places=3) … -
Reading all the image files in a folder in Django
I am trying to create a picture slideshow which will show all the png and jpg files of a folder using django. Problem is how do I open windows explorer through django and prompt user to choose a folder name to load images from. Once this is done, how do I read all image files from this folder ? Can I store all image files from this folder inside a list and pass this list in template views through context ? Please suggest me any optimum approach for this. Any help would be greatly appreciated.