Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to fix access token expiry error in azure cli
After login i am receiving this error. ERROR: The access token expiry UTC time '2/10/2019 6:26:39 AM' is earlier than current UTC time '2/10/2019 7:35:04 AM'. -
Django model.objects.all() queryset not displaying content - how to fix?
I'm learning Django and trying to setup some dynamic pages. I've mapped url's to /restaurants and /restaurants/mexican however my html content block is not displaying anything from my queryset. Code below: views.py def restaurantListView(request): template_name = 'restaurants/restaurants_list.html' queryset = Restaurant.objects.all() context = { "objectList": queryset } return render(request, template_name, context) class RestaurantListView(ListView): queryset = Restaurant.objects.all() template_name = 'restaurants/restaurants_list.html' class MexicanRestaurantListView(ListView): queryset = Restaurant.objects.filter(category__iexact='mexican') template_name = 'restaurants/restaurants_list.html' class AsianFusionRestaurantListView(ListView): queryset = Restaurant.objects.filter(category__iexact='asian fusion') template_name = 'restaurants/restaurants_list.html' urls.py from restaurants.views import ( restaurantListView, RestaurantListView, MexicanRestaurantListView, AsianFusionRestaurantListView, ) urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='home.html')), path('restaurants/', RestaurantListView.as_view()), path('restaurants/mexican/', MexicanRestaurantListView.as_view()), path('restaurants/asian/', AsianFusionRestaurantListView.as_view()), path('about/', TemplateView.as_view(template_name='about.html')), path('contact/', TemplateView.as_view(template_name='contact.html')), ] restaurants_list.html {% extends "base.html" %} {% block head_title %} Restaurants || {{ block.super }} {% endblock %} {% block content %} <h1>Restaurant List</h1> <ul> {% for obj in objectList %} <li>{{ obj.name }} | {{ obj.location }}</li> {% endfor %} </ul> {% endblock content %} I expected the items of Restaurant.objects.all() to be displayed in my content block on restaurants.html, but instead nothing is displaying. Same occurs for objects.filter() on the /restaurants/mexican route. -
How to make a `OneToOneField` compulsary in django?
How to make a OneToOneField compulsary in django? I tried doing this device = OneToOneField('Device', on_delete=models.CASCADE, blank=False, null=False) but I am still able to create the concerned model's object without a device Please advise. -
Is there any way to generate a standard response message to the request in drf
I am building an api using Django DRF. The api is working pretty fine. But it is generating different responses, for different kinds of errors. Suppose, if I add a feature of user registration. I am handling some erros in serializers using serializers.ValidationError function. But this is changing the response for different errors. I only want the response in standard manner of {"message": "reason for the error", "error": 1}. I don't want to hard code it. I mean I have used in multiple functionalities, so I have to hard code all the places. Hence, is there any better solution, like adding a function to the serializer and generating the response from that ??? class UserSerializer(serializers.ModelSerializer): confirm_password = serializers.CharField(max_length=50, required=True, validators=[password_check], write_only=True) password = serializers.CharField(max_length=50, required=True, validators=[password_check]) Id = serializers.CharField(max_length=100, required=False, allow_blank=True) user_type = serializers.CharField(max_length=30, required=True, write_only=True) email = serializers.EmailField(required=True) def validate_username(self, username): if User.objects.filter(username=username): raise serializers.ValidationError('Username already chosen!') if len(username) < 8: raise serializers.ValidationError('Username min length is 8') return username def validate_email(self, email): try: validate_email(email) except ValidationError: raise serializers.ValidationError('Enter a valid email') if User.objects.filter(email=email): raise serializers.ValidationError('Email already chosen!') return email def validate(self, attrs): key = 0 try: if models.Profile.objects.filter(userid=attrs['Id']).exists() and attrs['Id'] != '': raise serializers.ValidationError('UserId already chosen') if attrs['Id'] == … -
Play Audio from url on click in background of django template
Problem: once changing this java script snipped to take the element in as a parameter, the audio no longer plays on click I've found several posts regarding this topic but nothing that leads me to a correct answer. I've tried this several ways but haven't had success. Basically, I am trying to play an audio file in the background on the click of an element. The page is definitely pulling down all the audio files according to the network inspection, but the play is not occurring. What am I missing? This is generated by a django template. The template generates hundreds of the following code <div>'s <html> <head> <script> function play(audioid){ var audio = document.getElementById(audioid); audio.play(); } </script> </head> <body> <!-- repeated by template loop --> <span class="text-justify" data-feather="layers"> &nbsp; <i class="fas fa-play-circle" onclick="play(10audio)" title="Play Audio Clip"></i> <audio id="10audio" src="https://d7mj4aqfscim2.cloudfront.net/tts/zs/jiaoling/token/知道"></audio> &nbsp; <a href="#" title="Practice"> <i class="fas fa-dumbbell"></i> </a> &nbsp; <a href="#10" class="text-muted" title="Subject Helper Text"> 知道 </a> </span> </body> </html> -
Django: Replacing piece of url with integer variable
I am trying to replace a url call with a variable as follows: href="{% url 'educators:pay_patient' 9 %}".replace(/9/, x) And the value x is just a primary key of a model, i.e. x=1,2,3, etc.. My issue is that it seems that the number of digits of x and the number it is replacing has to match. For example, x=1 works with 9 but not 90. if x=1, href="{% url 'educators:pay_patient' 90 %}".replace(/90/, x) yields a 404 error with Request URL: http://127.0.0.1:8000/educators/study/pay/90/ How do I make this scheme generalizable for any number of digits of x? -
Django user profile No Profile matches the given query at
when user signup, it will create an user profile at the time. column id in account.user table has FK with created_by in profile table Register/views.py class RegisterFormView(TemplateView): template_name = 'home/register.html' def get(self, request, *args, **kwargs): regis_form = RegisterForm() return self.render_to_response({ 'base_url' : settings.BASE_URL, 'regis': regis_form, }) def post(self, request, *args, **kwargs): if request.method == 'POST': regis_form = RegisterForm(request.POST) if regis_form.is_valid(): user = regis_form.save() user.full_name = regis_form.cleaned_data.get("full_name") user.email = regis_form.cleaned_data.get("email") user.phone_number = regis_form.cleaned_data.get("phone_number") user.set_password(regis_form.cleaned_data.get("password")) password = regis_form.cleaned_data.get("password") profile = Profile.objects.create(created_by=user) user.save() user = authenticate(phone_number=user.phone_number, password=password) login(request, user) messages.success(request, "Register success") return redirect(reverse("home:register-success")) else: regis_form = RegisterForm(request.POST) return self.render_to_response({ 'base_url' : settings.BASE_URL, 'regis': regis_form, }) Profile/views.py class ProfileView(TemplateView): template_name = 'accounts/index.html' def get(self, request, user_id): data = get_object_or_404(Profile, pk=user_id) return self.render_to_response({ 'base_url' : settings.BASE_URL, 'data' : data, }) Profile/urls.py url(r'^(?P<user_id>\d+)/$', ProfileView.as_view(), name='profile'), Template/base.html <a class="dropdown-item" href="{% url 'profile:profile' user.id %}">Profile</a> register and create profile has succeess but I cannot access user profile page, i have an error No Profile matches the given query. -
Python, Django: ImportError: No module named local
I'm trying to run the file manage.py, whose code is below #!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django # noqa except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise # This allows easy placement of apps within the interior # myproject directory. current_path = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_path, 'myproject')) execute_from_command_line(sys.argv) with the following command: python manage.py runserver_plus 0.0.0.0:8000 But I'm getting the following traceback: Traceback (most recent call last): File "manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named local I don't know how to interpret this traceback … -
Keep getting this error not sure why "Can't convert 'set' object to str implicitly"
@admin.register(Book) class BookAdmin(ImportExportActionModelAdmin): resource_class = BookResource def get_import_form(self): return CustomImportForm def get_resource_kwargs(self, request, *args, **kwargs): rk = super().get_resource_kwargs(request, *args, **kwargs) rk['input_author'] = None if request.POST: author = request.POST.get('input_author', None) if author: request.session['input_author'] = author else: try: author = request.session['input_author'] except KeyError as e: raise Exception("Context failure on row import" + {e}) rk['input_author'] = author return rk Have this code in django admin page, but getting an error during the export. Can anyone let me know where is the issue? -
How to create a form to handle a model OneToOneField to AbstractBaseUser?
After spending 6 months using only django-rest-framework, this last week I needed to use django forms and templates for a simple application (university works XD). So I subclassed the AbstractBaseUser on MyUserModel (almost exactly like the official documentation) to define USERNAME=email, and I created a OneToOneField relation to MyUserModel. I'm not sure how to handle the 2 forms to make it work on creating a user. (I have done the exactly same thing with rest-framework a few months ago, just not sure how to handle it on forms and inside the view) Created MyUser model, e-mail is the USERNAME field. There is first_name, last_name. Company model, with some extra info and a OneToOneField to MyUser. Employees model, with extra info and a OneToOneField to MyUser. From here... How can I proceed to create a Employees user or a Company User, I mean the form view and signup template, If I'm able to create one, the other one will be easy. class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="E-mail", max_length=255, unique=True) first_name = models.CharField(verbose_name="First Name", max_length=255) last_name = models.CharField(verbose_name="Last Name", max_length=255) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) class Company(models.Model): company = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) register_number = models.BigIntegerField(verbose_name="register") aactivity = models.CharField(verbose_name="Company activity", max_length=255) class Employees(models.Model): … -
How to use FileField with digitalocean storage?
I'm trying to setup my django app to use digitalocean storage. I'm currently uploading files simply through the admin panel. I've done the following config in my settings.py: AWS_DEFAULT_ACL = None AWS_ACCESS_KEY_ID = 'XXX' AWS_SECRET_ACCESS_KEY = 'xxx' AWS_STORAGE_BUCKET_NAME = 'tickets' AWS_S3_ENDPOINT_URL = 'xxx' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'ticketfiles' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'ticketfulfillment/static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' When I upload a file, I don't get any errors, but when I check my storage bucket in digitalocean I don't see the files there, and I cannot access them on my app either. Can anyone give me guidance on uploading files to digitalocean storage through a FileField in django? -
Django custom template without form.as_p
I am trying to implement custom password reset form in Django. I got my custom template loaded and functionality worked using {{ form.as_p }} However, I want to use my own fields instead of {{ form.as_p }}. Here's my form, <form method="post" action="/accounts/password_reset/complete"> {% csrf_token %} <label>New Password</label> <input type="password"> <label>Re-enter new password<label> <input type="password"</input> <button type="submit">Reset Password</button> </form> However, on submission it gives me Method Not Allowed (POST) 405 error. Am I missing on something? -
when i run it it giving me errors please tell me how i get data from database
class Class_dtl_View(DetailView): template_name='temp/detail_view.html' queryset=Tweets.objects.all() def get_context_data(self,**kwargs): context=super().get_context_data(**kwargs) context['now']=timezone.now() return context url.py file urlpatterns = [ path('', views.home,name='home'), path('<slug:slug>/',Class_dtl_View.as_view(),name='dtl'),] model.py class Tweets(models.Model): user =models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) content_1=models.CharField(max_length=200) updated =models.DateTimeField(auto_now=True) timestamp=models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) http://localhost:8000/dtl/ FieldError at /dtl/ Cannot resolve keyword 'slug' into field. Choices are: content_1, id, timestamp, updated, user, user_id Request Method: GET Request URL: http://localhost:8000/dtl/ Django Version: 2.1.5 Exception Type: FieldError Exception Value: Cannot resolve keyword 'slug' into field. Choices are: content_1, id, timestamp, updated, user, user_id Exception Location: D:\django\lib\site-packages\django\db\models\sql\query.py in names_to_path, line 1389 -
Creating a search filter in django rest framework
I am trying to make a user search for images, I have gone through the doc but I can't understand. I have installed Django-filter but I am getting this error TypeError: __init__() got an unexpected keyword argument 'many' The goal is for users to search or filter posts by 'tags','owner' or 'image_url' Comment model class Photo(models.Model): post = models.TextField(max_length=140, default="") image_file = models.ImageField(upload_to='public/images', default='image.png') image_url = models.CharField(max_length=140, default='image.png') date_uploaded = models.DateTimeField(auto_now=True) owner = models.ForeignKey('auth.User', on_delete=models.CASCADE,) tags = models.CharField(max_length=10, default='img') class Meta: ordering = ('date_uploaded',) def __str__(self): return self.post view.py class PhotoSearchList(generics.ListAPIView): model = Photo serializer_class = PhotoFilterSerializer queryset = Photo.objects.all() filter_backends = (filters.SearchFilter,) filter_fields = ('tags', 'date_uploaded') Serializer.py class PhotoFilterSerializer(filters.FilterSet): class Meta: model = Photo fields = ('tags', 'date_uploaded') urls.py path('search/', views.PhotoSearchList.as_view()), In the settings I added this as mentioned in the doc REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',) } I have also added 'django_filters' to INSTALLED_APPS in the setting -
Django toggle boolean field
i try to toggle boolean field, I know that is simple in normal situation. But I need to toggle boolean field with foreignkey. I have two models. Model 1: Goal and model 2: Joined(foreignkey to Goal), i try to create this because activity feed (get stream.io)show only one activity - when user add goal. But i need also activity when user join to goal. That why i create joined model for second activity. Model 2 have only 4 fields: joined(boolean), user(foreign to user), created_at and goal(foreignkey to model Goal) How to create view and path to work with. I try this: @login_required def toggle_done(request, joined_id: int) -> HttpResponse: joined = get_object_or_404(Joined, pk=joined_id) toggle_task_completed(joined.id) messages.success(request, "Dołączyłeś do celu '{}'".format(joined.goal.title)) return redirect( reverse('goallist') ) def toggle_task_completed(joined_id: int) -> bool: try: joined = Joined.goal.get(id=joined_id) joined.joined = not joined.joined joined.save() return True except Joined.DoesNotExist: # FIXME proper log message print("Nie znaleziono celu") return False #Path: path('toggle_done/<int:joined_id>/', views.toggle_done, name='joined'), And template: {% if goal.joined %} <a href="{% url 'joined' goal.id %}" class="btn btn-success-gradiant">Już dołączyłeś</a> {% else %} <a href="{% url 'joined' goal.id %}" class="btn btn-danger-gradiant">Dołącz do celu</a> {% endif %} Link: http://django.local:8000/goals/toggle_done/1/ Id is good, but when i click link: No Joined matches the given … -
VS 2017 Python/Django Template- CSS doesn't work but inline styling does
I am working on a template generated from VS 2017 Community for Python/Django web application. I can't seem to get the CSS to work. I looked at the page source and it is referencing the correct style sheet.I adding a class (class="test") to to h4 in the .html file so that I can target it through the CSS in the site.css I have .test{ `color: red;' } background, I started by trying to add a "tooltip" to this sheet. When that didn't work I went back to a simple manipulation just to see if I could get that to work. Please let me know if you need other code snippets! other aspects of the code work as expected it's just styling that is giving me fits. Pretty new at this so please be just a little forgiving! :) -
JQuery on dynamically generated html tables
I have multiple HTML tables generated dynamically. Each row on the tables has an Edit button. With the following code, the click event only fires for the buttons on the first table. It doesn't work for the subsequent tables. Please help me to make it work for all the tables. In my Django template: {% for parent in parents %} <table class="table" id="my-table"> <thead> <tr> <th>Name</th> <th>Age</th> <th></th> </tr> </thead> <tbody> {% for child in parent.children %} <tr> <td>{{ child.name }}</td> <td>{{ child.age }}</td> <td> <button type="button" class="btn-edit" data-url="{% url "app:child-update" child.id %}"> <span class="glyphicon glyphicon-pencil"></span> Edit </button> </td> </tbody> </table> {% endfor %} JavaScript code: $(function () { var loadForm = function () { // .... } }; $("table").on("click", ".btn-edit", loadForm); -
How to separate models fields by role or group in Django
I have app called Fruits with two users type Seller and Buyer. Each user type have a different fields: Seller has fields Phone number Location Shop name Open hours Buyer has fields Phone number Address Because each user have phone number fields so I create this fields in Django user model like this; models.py from django.db import models from django.contrib.auth.models import AbstractUser # Master class User(AbstractUser): telephone = models.PositiveIntegerField(null=True, blank=True) class Meta: permissions = ( ("seller", "Seller"), ("buyer", "Buyer"), ) # Seller class Customer(models.Model): user = models.OneToOneField(User, verbose_name="user_id", db_column="user_id", related_name="profile", on_delete=models.CASCADE) location = models.CharField(max_length=255, null=True) shop_name = models.CharField(max_length=255, null=True) open_hours = models.TextField(max_length=500, null=True) # Buyer class Customer(models.Model): user = models.OneToOneField(User, verbose_name="user_id", db_column="user_id", related_name="profile", on_delete=models.CASCADE) address = models.TextField(max_length=500, null=True) And in admin.py; from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.forms import TextInput, Textarea, NumberInput from django.db import models from .models import User from .models import Seller from .models import Buyer admin.site.register(User) class SellerProfileInline(admin.StackedInline): model = Seller can_delete = False verbose_name = "Seller Profile" verbose_name_plural = "Seller Profile" fk_name = "user" class BuyerProfileInline(admin.StackedInline): model = Buyer can_delete = False verbose_name = "Buyer Profile" verbose_name_plural = "Buyer Profile" fk_name = "user" class CustomUser(UserAdmin): inlines = [SellerProfileInline, BuyerProfileInline] … -
How to login before management command
I have a bunch of code where I do things with the current user( setting created_by field , sending mail on creation of certain records). But as far as I know you don't have a logged in user in your management command, so the question is, how can I run management commands as a valid logged in user? -
Getting the cleaned_data of a CharField with Choice from Django
I'm trying to retrieve the data of a form that belongs to a CharField that uses choice in Django. I have the following models.py: class Transaccion(models.Model): ref = models.CharField(max_length=20, primary_key=True) fecha = models.DateField(default=timezone.now) usua = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) monto = models.FloatField(max_length=50, blank=True, null=True) TYPE_TRANS = ( ('d', 'Debito'), ('c', 'Credito'), ) tipo = models.CharField(max_length=1, choices=TYPE_TRANS) LOAN_STATUS = ( ('a', 'Aprobada'), ('e', 'Pendiente'), ('c', 'Rechazada'), ) estado = models.CharField(max_length=1, choices=LOAN_STATUS, blank=True, default='e') TYPE_BANCO = ( ('BBVA', 'Bco BBVA Provincial'), ('BOD', 'Banco Occidental de Descuento'), ('MER','Bco Mercantil') ) bco = models.CharField(max_length=4, choices=TYPE_BANCO, blank=True) The following forms.py: class GestionarTransaccionForm(forms.ModelForm): class Meta: model = Transaccion fields = [ 'usua', 'fecha', 'bco', 'ref', 'monto', 'tipo', 'estado', ] widgets={ 'usua': forms.TextInput(attrs={'class': 'form-control', 'readonly': True}), 'fecha': forms.TextInput(attrs={'class': 'form-control', 'readonly': True}), 'bco': forms.Select(attrs={'class': 'form-control', 'readonly': True}), 'ref': forms.TextInput(attrs={'class': 'form-control', 'readonly': True}), 'monto': forms.TextInput(attrs={'class': 'form-contol', 'readonly': True}), 'tipo': forms.Select(attrs={'class': 'form-control', 'readonly': True}), 'estado': forms.Select(attrs={'class': 'form-control'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['ref'].disabled = True self.fields['fecha'].disabled = True self.fields['usua'].disabled = True self.fields['monto'].disabled = True self.fields['tipo'].disabled = True self.fields['bco'].disabled = True And this views.py: class GestionarTransaccion(UpdateView): model = Transaccion form_class = GestionarTransaccionForm template_name = "administrador/gestionarT.html" success_url = reverse_lazy('transManager') def form_valid(self, form): instance = form.save(commit=False) u = User() if form.cleaned_data['estado']=='Aprobado': … -
Django get a clean return from subprocess.Popen at celery
i have a celery task that calls a subprocess.Popen aka shell cmd but for some reasone not the output of the cmd gets saved to the user field but the process memory id !?!? [2019-02-09 21:35:05,526: INFO/MainProcess] Received task: MyProject.tasks.allocate_new_btc_address[08d7db34-5710-4224-be07-c968599d9039] [2019-02-09 21:35:05,540: WARNING/ForkPoolWorker-9] <subprocess.Popen object at 0x7f31063d79b0> [2019-02-09 21:35:05,540: INFO/ForkPoolWorker-9] MyProject.tasks.allocate_new_btc_address[08d7db34-5710-4224-be07-c968599d9039]: New BTC address has been allocated to a user account [2019-02-09 21:35:05,540: INFO/ForkPoolWorker-9] Task MyProject.tasks.allocate_new_btc_address[08d7db34-5710-4224-be07-c968599d9039] succeeded in 0.012948354000400286s: None 1yxeepwsdzt6n4XtgdwqLrWqCHXdeVfHD tasks.py @app.task def allocate_new_btc_address(user_pk): user = User.objects.get(pk=user_pk) new_address = subprocess.Popen(['electrum', 'createnewaddress']) try: user.acc_btc_addr = new_address user.save() print(new_address) logger.info("New BTC address has been allocated to a user account") except Exception as e: print(e) thats the vaule that gets saved to the field: <subprocess.Popen object at 0x7f31063d79b0> thanks in advance -
Heroku does not find module when local version does
The problem So, I have made a website with multiple home made apps. I now want to deploy this website using heroku. This doesn't work however, as I keep getting errors relating to heroku not being able to find the apps. When I run the website locally with python manage.py runserver everything behaves as expected. When I however try to deploy this website using Heroku I get an error (stacktrace provided underneath). Project structure towima | .gitignore | Procfile | README.md | requirements.txt | runtime.txt | tree.txt | +---media_cdn | | .DS_Store | | | \---products | \---towima | .DS_Store | db.sqlite3 | manage.py | pharma_locations.json | __init__.py | +---accounts | | admin.py | | apps.py | | forms.py | | models.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations +---api | | admin.py | | apps.py | | models.py | | serializers.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations | +---orders | | admin.py | | apps.py | | forms.py | | models.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations | +---pharmacies | … -
Display a var in template using Ajax and Django
I'm new to using Ajax calls with Django. Im trying to implement a simple Display or not display depending on the type of get called by Ajax: Views: def dynamic(request): context = {} if request.method == 'GET': if 'backtest_type' in request.GET: context['display_details'] = False print ('Im not displaying') elif 'change_val' in request.GET: context['display_details'] = True print ('Im displaying') else: context['display_details'] = False return render(request, "demo/dynamic.html", context) In my template: {% extends 'demo/base.html' %} {% block body %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <link rel="stylesheet" href="{% static 'css/dynamic.css' %}"> <script> $(document).on('click','#id_backtest_type', function () { console.log( $(this).val() ); $.ajax({ url: "data-url", type: 'get', data: {'backtest_type': 1}, success: function (data) { console.log('data sent ' + data); }, failure: function(data) { alert('Got an error dude'); } }); }); $(document).on('click','#btnClick', function () { // console.log( $(this).val() ); $.ajax({ url: "data-url", type: 'get', data: {'change_val': 1}, success: function (data) { console.log('data sent ' + data); failure: function(data) { alert('Got an error dude'); } }); }); </script> <div> {% if display_details %} <h1>I'm diplaying</h1> {% endif %} </div> <div id="btnClick" class="col-sm-4"> <div class="btn-group btn-group-justified" role="group"> <div class="btn-group" role="group"> <button class="btn btn-secondary" type="button">Don't Display</button> </div> </div> </div> <div id="id_backtest_type" class="col-sm-4"> <div class="btn-group btn-group-justified" role="group"> <div class="btn-group" role="group"> <button class="btn btn-secondary" type="button">Display!</button> … -
Django - Extended UserAdmin but have no customUser instance for Model
Im building a webapp w/ django where users are defined by a "Student" Model in which I use a OneToOneField to extend the default User django provides from django.contrib.auth.models import User ... class Student(models.Model): """Model representing Student Users""" user = models.OneToOneField(User, on_delete=models.CASCADE) birthday = models.DateField(null=True, blank=True) def get_absolute_url(self): """Returns the url to access a particular user instance.""" return reverse('student-detail', args=[str(self.id)]) def __str__(self): return self.user.username In the app, users are able to post "Projects" which are defined by a Project Model in which I use a foreignKey to associate a Project w/ a Student class Project(models.Model): title = models.CharField(max_length=200) # ForeignKey - FOUNDER (STUDENT) of project founder = models.ForeignKey(Student, on_delete=models.SET_NULL, null=True) description = models.TextField(max_length=2000) def __str__(self): """String for representing the Model object.""" return self.title I created a view that shows me only the projects that my logged in user has created under the route http://localhost:8000/home/myprojects However, despite being logged in, I get this error when I try to route to this page: If I go back to my Project Model and change class Project(models.Model): # ForeignKey - FOUNDER (STUDENT) of project founder = models.ForeignKey(Student, on_delete=models.SET_NULL, null=True) To class Project(models.Model): # ForeignKey - FOUNDER (USER) of project founder = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) … -
Django: Set the Selected Value of ChoiceField when using a FormView
I'm displaying a form using a FormView, but I need to set a selected ChoiceField when page renders, e.g. set a default selection. Acoording to a releted Question, I need to: Try setting the initial value when you instantiate the form: Setting the selected value on a Django forms.ChoiceField I don't know how to do it. forms.py class StepOneForm(forms.Form): size = forms.ChoiceField(choices=TAMANIOS, widget=forms.RadioSelect(), label='Selecciona un tamaño') quantity = forms.ChoiceField(choices=CANTIDADES, widget=forms.RadioSelect(), label='Selecciona la cantidad') class StepTwoForm(forms.ModelForm): comment = forms.CharField(widget=forms.Textarea) class Meta: model = CartItem fields = ('file', 'comment') def __init__(self, *args, **kwargs): super(StepTwoForm, self).__init__(*args, **kwargs) self.fields['comment'].required = False self.fields['file'].required = False def save(self, commit=True): instance = super(StepTwoForm, self).save(commit=commit) return instance I've also tried seeting initial=1 without success: class StepOneForm(forms.Form): size = forms.ChoiceField(choices=TAMANIOS, widget=forms.RadioSelect(), label='Selecciona un tamaño', initial=1) quantity = forms.ChoiceField(choices=CANTIDADES, widget=forms.RadioSelect(), label='Selecciona la cantidad') views.py class StepOneView(FormView): form_class = StepOneForm template_name = 'shop/medidas-cantidades.html' success_url = 'subir-arte' def get_initial(self): # pre-populate form if someone goes back and forth between forms initial = super(StepOneView, self).get_initial() initial['size'] = self.request.session.get('size', None) initial['quantity'] = self.request.session.get('quantity', None) initial['product'] = Product.objects.get( category__slug=self.kwargs['c_slug'], slug=self.kwargs['product_slug'] ) return initial def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['product'] = Product.objects.get( category__slug=self.kwargs['c_slug'], slug=self.kwargs['product_slug'] ) return context def form_invalid(self, form): print('Step one: form is NOT …