Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I access my static files from my Django app?
I have a Django app running in a Docker container. I am using Nginx to serve as the production server with a docker-compose file putting the app, Nginx and Postgres together in a network of containers. I set up my Dockerfile as follows: FROM python:3.9.6-buster ENV HOME=/home/app/ ENV APP_HOME=/home/app/web RUN mkdir -p "${APP_HOME}/staticfiles" # Create user ENV PYTHONBUFFERED=1 WORKDIR $APP_HOME COPY requirements.txt $APP_HOME RUN pip install -r requirements.txt COPY . $APP_HOME which as you can see sets a staticfiles directory. However, following normal Django principals my file structure is /home/app/web/quote_checklist/static/quote_checklist when I exec into the web container. I'm using the following in my settings.py BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") When I access the index page I am getting an error that the directory/file /home/app/web/staticfiles/quote_checklist/css/base.css is not found, suggesting my app is looking in this staticfiles directory, which has nothing in it. I tried removing the /staticfiles/ bit from my static volume as well but then the system just looks in /home/app/web/static/quote_checklist/css/base.css rather than following the normal Django path, which would be to look in quote_checklist/static/quote_checklist/css/base.css. Does anyone have suggestions? -
Creating object with generics CreateApiView 'request' required
This is my serializer and Viewset, i want to create an instance of Like if someone likes a product (Post request 'products/product:id/like'). But i get an error that 'request' is required. class LikeSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) product = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Like fields = ('user', 'product',) class LikeProductApi(generics.CreateAPIView): queryset = Like.objects.all() serializer_class = LikeSerializer def create(self, request, *args, **kwargs): product_id = self.kwargs['pk'] product = ProductInStore.objects.get(id=int(product_id)) if Like.objects.filter(user=self.request.user, product=product).exists(): raise ValidationError(_("This user already likes this product")) else: return super().create(user=self.request.user, product_id=product_id, **kwargs) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/generics.py", line 190, in post return self.create(request, *args, **kwargs) File "/Users/jakubstrawa/programming/PythonKuba/api/ecommerce/views.py", line 124, in create return super().create(user=self.request.user, product_id=product_id, **kwargs) TypeError: create() missing 1 required positional argument: 'request' Do you have any idea why? -
Division between two annotations
I'm creating those two annotations as it follows: cs = Champion.objects.all() total_games = Match.objects.all().count() cs = cs.annotate( picked_games=Count( expression='participants__match__id', filter=Q(participants__role='BOTTOM'), distinct=True ), total_games=Value(str(total_games), output_field=IntegerField()) ) And everthing's alright until here. I fetch both the picked_games and total_games with correct results. >>> cs.get(name='Jhin').picked_games 27544 >>> cs.get(name='Jhin').total_games 97410 However, if i try to divide one by another: cs = cs.annotate( pick_rate=ExpressionWrapper( expression=F('picked_games') / F('total_games'), output_field=FloatField() ) ) This results on a 0: >>> cs.get(name='Jhin').pick_rate 0.0 I don't understand what's problem here.. I can get the result if divide them externally, so why can't i get the result on a different column for the whole queryset? >>> cs.get(name='Jhin').picked_games / cs.get(name='Jhin').total_games 0.28319474386613286 -
My email isn't sending with django, giving weird errors
This is my settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'my_email' EMAIL_HOST_PASSWORD = 'my_password' This is the views.py (shortened): from django.core.mail import send_mail send_mail( 'Test available', available_tests, 'from_email', ['to_email'], fail_silently=False, ) I get this error when I run it: SMTPAuthenticationError at /tests/ (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbt\n5.7.14 tw36yR7hn8otxR29NEQL37XEj4odHZyoNuW6V9x_AMqT-nzMaVhpV27LiIgjAi7lr2GKo\n5.7.14 Ec1mJIx6e--XhSr_V31TVZe6UfjUhrShxE-UwxoTZhF2RTS-X5zesGeo3NZf53B7>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 t11sm23243834qtx.16 - gsmtp') Request Method: GET Request URL: https://myapp.herokuapp.com/tests/ Django Version: 4.0.1 Exception Type: SMTPAuthenticationError Exception Value: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbt\n5.7.14 tw36yR7hn8otxR29NEQL37XEj4odHZyoNuW6V9x_AMqT-nzMaVhpV27LiIgjAi7lr2GKo\n5.7.14 Ec1mJIx6e--XhSr_V31TVZe6UfjUhrShxE-UwxoTZhF2RTS-X5zesGeo3NZf53B7>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 t11sm23243834qtx.16 - gsmtp') Exception Location: /app/.heroku/python/lib/python3.9/smtplib.py, line 662, in auth Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.10 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Thu, 17 Feb 2022 21:48:04 +0000 I've allowed less secure apps in my google account, I've clicked that it was me in the email, how do I fix it? -
Django how to automatically render name of patient if exact value matched?
I have an forms for set appointment. see the picture If any patient fill the mobile number and he already exist in my database then I want to automatically render his name in my patient name fields. Suppose I have an patient name Jhone and his mobile number +123456. If Jhone input his mobile number then I want his name will be automatically render in my patient name fields. How to that in djago? here is my code: models.py class Patient(models.Model): patient_name = models.CharField(max_length=150) patient_number = models.CharField(max_length=50, blank=True, null=True) class Appointment(models.Model): patient = models.ForeignKey( Patient, on_delete=models.CASCADE, blank=True, null=True) patient_name = models.CharField(max_length=100, blank=True, null=True) patient_number = models.CharField(max_length=50, blank=True, null=True) views.py: if form.is_valid(): form.save() messages.add_message(request, messages.INFO,f'Appoinment added sucessfully for {form.instance.patient_name}') return redirect('hospital:add-appointment') else: form = AppointmentForms() -
synchronization between SQL local db and MYSQL on server
I have Desktop Application with SQL local DB and Web app with Django and mysql Database whats the best method to sync the local clients which is more than 50 user with only oner server and its mysql which method work perfect in this section -
Requests to AWS using Django not using correct parameters on all files
I have a Django application that upon loading the admin, only receives 4 out of 6 of the necessary static files. The difference between the 4 successful and the 2 failed is that the following paramters are not present in the failed requests: X-Amz-Algorithm X-Amz-Credential X-Amz-Date X-Amz-Expires X-Amz-SignedHeaders X-Amz-Signature However the parameters are present in the request headers referer. Also it is consistently the same 2 files. And yes they exist as I will mention further down in this question. I installed django-storages and boto3 to work with AWS. Here are the relevant settings from settings.py: INSTALLED_APPS = [ ... 'storages', ... ] AWS_S3_ACCESS_KEY_ID = 'my-access-key' AWS_S3_SECRET_ACCESS_KEY = 'my-secret-access-key' AWS_STORAGE_BUCKET_NAME = 'my-bucket-01' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = 'eu-west-2' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_ADDRESSING_STYLE = "virtual" A successful request: https:// my-bucket-01.s3.eu-west-2.amazonaws.com/admin/css/responsive.css?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=my-access-key%2F20220217%2Feu-west-2%2Fs3%2Faws4_request&X-Amz-Date=20220217T212138Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=31bc0e43fcc693f70c7662432ee6d88d8358652894611a0f7387ac35febf5ef9 A failed request: https:// my-bucket-01.s3.eu-west-2.amazonaws.com/admin/css/fonts.css Failed requests referer: https:// my-bucket-01.s3.eu-west-2.amazonaws.com/admin/css/base.css?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=my-access-key%2F20220217%2Feu-west-2%2Fs3%2Faws4_request&X-Amz-Date=20220217T212138Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=af8fb82686dd0dcc2600eebdf9ceecec482dd44be02a3c3f3a9b793f96cee617 I went to the link in the referer and it worked. So my question is either: Why do only some of my requests include the correct parameters and how do I get them to use the correct ones? or How do I force the requests to use the referers? -
Filter urlencode with 2 Level reverse relationship
I have these models: class Issuer(models.Model): name = models.CharField() @property def investor_count(self): return Investment.objects.filter(offering__issuer_id=self.pk).count() or 0 def __str__(self): return self.name class Offering(models.Model): issuer = models.ForeignKey(Issuer, on_delete=models.CASCADE) name = models.CharField() def __str__(self): return self.name class Investment(models.Model): offering = models.ForeignKey(Offering, on_delete=models.CASCADE) name = models.CharField() def __str__(self): return self.name And I want to display in the Issuer list view the number of investments it has. This is the function I'm currently using, # link investments to page def view_investments_link(self, obj): count = obj.investor_count url = ( reverse("admin:crowdfunding_investment_changelist") + "?" + urlencode({"issuer__id": f"{obj.id}"}) ) return format_html('<a href="{}">{} Investment(s)</a>', url, count) view_investments_link.short_description = "NUMBER OF INVESTMENTS" And this is how it looks: But the line + urlencode({"issuer__id": f"{obj.id}"}) does not work. It changes my url to http://localhost:8000/app/investment/?e=1. Is there a way to filter Investments using the issuer_id? -
send form after paypal payement is approuve
hello I am working with django I have a form that should be posted if the paypment is done, I don't know what should I do exaclty I tried but doesn't work for me, anyways in my html page I have a form and submit button and then the paypal payment <div id="paypal-button-container"></div> -
How to reload the current page when form was sent?
Hey, after the form was sent the page needs to be automatically reloaded / refreshed. Either just the current page is going to be reloaded or the variable slug_title (which would be part of the current page url) needs to be passed into the (' ') from HttpResponseRedirect. Do you have any suggestions? I would really appreciate it. :) views.py def posts(request, slug_titel): post = get_object_or_404(Thread, slug_titel=slug_titel) form = ThreadForm() if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(' ') # <- here I need to put in slug_title from above -
How to add multiple values to checkbox field? Django
I am have a form with a checkbox field and hidden price field inside for loop like this: {% for item in inventory %} <input type="checkbox" name="item_name" id="{{forloop.counter}}" value="{{item.name}}"> <input type="hidden" name="item_price" value="{{item.price}}"> {% endfor %} But I also want to add item.price of the selected item to it. Basically I would like to get the data from views like this: item_name = request.POST.getlist('item_name') price = request.POST.getlist('price') Which would both have a list of chosen items. ['item name 1', 'item name 2'] ['item price 1', 'item price 2'] or together [['item name 1', 'item price 1']['item name 2', 'item price 2']] The second option would be better but I have no clue how to do that. Also I would like to add more values to it in the future. How do to do that? -
Listing objects field instead of Object in Django Rest Framework
I've got a model class Like(models.Model): product = models.ForeignKey('ProductInStore', on_delete=models.PROTECT) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) class Meta: unique_together = ('product', 'user',) and a serializer class LikeSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) product = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Like fields = ('user', 'product',) class UserLikedProductsApiList(generics.ListAPIView): queryset = Like.objects.all() serializer_class = LikeSerializer And so if someone likes a product, adds it to favourites, it creates an Like object in database. And i want to create an endpoint users/me/likedProducts so that i can list all the products that self.user.request has liked. Meaning all the Like instances but instead of Like instances i want to show only Like.product instances. Lets say a person x has liked 4 items, and i want to show only 4 items in that list. Do you have any idea how to get around that in Django Rest Framework? -
how to change an object when creating another object in django?
I am writing a financial accounting application. I am using drf. I can not figure out how to change the account when creating the "expense" object Models count = models.DecimalField(max_digits=7, decimal_places=2, verbose_name='Расход') date = models.DateField(blank=True, verbose_name='Дата', null=True) account = models.ForeignKey(Cash, on_delete=models.CASCADE, verbose_name='Счёт', default=DEFAULT_CHECK_ID) category = models.ForeignKey(Categories, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Категория') place = models.ForeignKey(Places, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Место платежа') comment = models.CharField(max_length=150, blank=True, verbose_name='Комментарий') is_income = models.BooleanField(verbose_name='Доход') Serializer class CountSerializer(serializers.ModelSerializer): category = serializers.CharField() place = serializers.CharField() account = serializers.CharField() Views class CountViewSet(ModelViewSet): queryset = Count.objects.all() serializer_class = CountSerializer filter_backends = [DjangoFilterBackend, SearchFilter] permission_classes = [IsAuthenticated] filter_fields = ['category', 'place'] search_fields = ['count'] def create(self, request): count = self for i in count: if i.is_income: account_id = i.account.id result = i.account.balance + i.count return Cash.objects.filter(id=account_id).update(balance=result) -
Django apostrophe escaping change
While upgrading Django I noticed that the html escape function used to translate an apostrophe into &#39; whereas it now translates it into &#x27;. I understand the old value is the HTML code and the new value is the hex code. The change seems to have come about because Django used to do the translation itself but now hands it off to python's html module. My question is, are these functionally equivalent? Are there any case where I would need to worry about this change? Also, in case I am not asking the right questions, can anyone direct me to what I should read to understand why these 2 types of codes exist and how they are used? -
How to add another model inside of first model with @property? django
I have Slot model, and OutletToSlot model. In OutletToSlot i can get Slot, but in slot i can't do it. So, I want to add second model inside my first model, why my solve doesn't work? class Slot(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE) outletsSlotInventory = models.ForeignKey(OutletsSlotInventory, on_delete=models.CASCADE) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class Meta: unique_together = [['owner', 'outletsSlotInventory']] @property def outletToSlot(self): outletToSlots = self.outletToSlot_set.all() myOutletsToSlots = outletToSlots.filter(owner.id=id); return myOutletsToSlots def __str__(self) -> str: return str(id) class OutletToSlot(models.Model): outletToSlotId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) expireTime = models.DateTimeField(blank=True) outlet = models.ForeignKey(Outlet, null=True, blank=True, on_delete=models.CASCADE, default=0) slot = models.OneToOneField(Slot, null=True, blank=True, on_delete=models.CASCADE) def __str__(self) -> str: return "{0} - {1}".format(self.outlet.label, self.slot) -
Create AutoCAD with Python
Is it possible to create an application like AutoCAD, 3D-Max, SketchUp with python and make it online? I mean creating a similar app from scratch, not using APIs! -
Django Image upload issue Cloundinary
i'm learning Django at present and just about getting to the deployment stage at hit a problem serving static/media with Cloudinary, following guides how to do this, it seems straight forward enough. I've checked the Cloudinary support but I can't find anything to help, just wondering if anyone has any input. The problem I have is that I am using Exiffield (to get image info) and ImageSpecField from ImageKit to resize the images for thumbnails and I think this is giving me problems with Cloudinary. Firstly I can't upload images from Admin, I get a Exception Value:Empty file error. Secondly I get 400 Client Error: Bad Request for url: https://res.cloudinary.com/ **path to file*** when trying to open my site (which is being served locally and in development This is using ImageField as upload. I would change it to CloudinaryField but my model heavily relies on ExifField which wont read from it. Model below. image = models.ImageField(upload_to='images') mid_thumbnail = ImageSpecField(source='image', processors=[ResizeToFit(220, 150)], format='JPEG', options={'quality': 100}) gallery_thumbnail = ImageSpecField(source='image', processors=[ResizeToFit(300, 250)], format='JPEG', options={'quality': 100}) gallery_detail = ImageSpecField(source='image', processors=[ResizeToFit(1000, 850)], format='JPEG', options={'quality': 100}) title = models.CharField(max_length=100) albums = models.ManyToManyField(Album, blank=True, related_name='photos') feature_image = models.BooleanField(default=False) description = models.CharField(editable=False, max_length=150, blank=True) posts = models.ManyToManyField(Post, blank=True, … -
Django - Paypal Cancel Suscription
I recently used the django-paypal library in my project. All is working fine, the only problem I'm facing is that I don't find the way to implement a cancel button (to cancel a suscription) or an upgrade button (to change the suscription plan). There is no mention of those buttons in the documentation, so I guess I'm asking this question here to confirm that it can't be achieved with the django-paypal library -
Django IndexError: list index out of range error
I am trying out this code i found online. When i tried commands like runserver, migrate and make migrations. All of them showed this error Traceback (most recent call last): File "C:\Django\OLD\ToDo_Application-master\ToDo_Application-master\todos\views.py", line 129, in check_time task() File "C:\Django\OLD\ToDo_Application-master\ToDo_Application-master\todos\views.py", line 155, in is_expired if splited_notification_time[1] == "minutes": IndexError: list index out of range CODE OF is_expired : def is_expired(): connection = sqlite3.connect('db.sqlite3') cursor = connection.cursor() cursor.execute( " SELECT * FROM todos_todo where email_notification != '' AND notification_time != 'None' AND sent_reminder == 'False' ") rows = cursor.fetchall() todo_notify_time = 0 for row in rows: todo_item_id = row[0] due_date_in_ms = int(datetime.fromisoformat(row[3]).timestamp() * 1000) current_date = int(datetime.now().timestamp() * 1000) splited_notification_time = str(row[6]).split(" ") receiver_email = row[5] sent_reminder = row[7] date_in_pst = due_date_in_ms - (7 * 60 * 60 * 1000) time_remaining = date_in_pst - current_date if splited_notification_time[0] != "None": if splited_notification_time[1] == "minutes": todo_notify_time = int( (splited_notification_time[0])) * 60 * 1000 elif splited_notification_time[1] == "hours": todo_notify_time = int( (splited_notification_time[0])) * 60 * 60 * 1000 elif splited_notification_time[1] == "day": todo_notify_time = int( (splited_notification_time[0])) * 60 * 60 * 24 * 1000 if time_remaining <= todo_notify_time: todo_item_expire = "Your todo_item name - " + \ str(row[1]) + " will expire in " + … -
Make select field toggle another field using Django Forms WITHOUT jQuery
How can I create a toggling behavior using Django form fields such as shown in the gif purely using Django? In the example below the user is prompted to choose only a Division or Center, if the division is chosen, center will automatically be prompted to None and vice versa. In order to create the effect shown, I am using jQuery and some beginner Django code: <div class="col-md-5"> <label>Division </label> <select id="division" name="division" class="form-control select2"> {%for division, name in divisions%} <option value="{{ division }}">{{ name }}</option> {% endfor %} </select> </div> <div class="col"> <h3><strong>OR</strong></h3> </div> <div class="col-md-5"> <label>Center</label> <select id="center" name="center" class="form-control select2"> {%for center, name in centers%} <option value="{{ center }}">{{ name }}</option> {% endfor %} </select> </div> $(document).ready(function () { // Set option selected onchange $("#center").change(function () { // Set selected if ($("#division").val() != "None" && $("#center").val() != "None") { $("#division").val("None"); $("#division").select2().trigger("change"); } return; }); $("#division").change(function () { // Set selected if ($("#division").val() != "None" && $("#center").val() != "None") { $("#center").val("None"); $("#center").select2().trigger("change"); } return; }); }); However the rest of my fields are declared using django forms: class NewTitlesForm07(forms.Form): def __init__(self, *args, **kwargs): super(NewTitlesForm07, self).__init__(*args, **kwargs) self.fields['start_month'] = forms.ChoiceField(choices=MONTH_CHOICES, widget=forms.Select(attrs={'class': 'select2 form-control'})) self.fields['start_year'] = forms.ChoiceField(choices=YEAR_CHOICES_07, widget=forms.Select(attrs={'class': 'select2 form-control'})) … -
Set value of GeoDjango map widget in change form based on other field using jQuery
I'm working on a project that uses GeoDjango and django-cities. I have one model: class Site(models.Model): name = models.CharField(max_length=60) assigned_to = models.ForeignKey( to=User, on_delete=models.PROTECT, null=True, blank=True ) country = models.ForeignKey( to=Country, on_delete=models.PROTECT, null=True, blank=True ) # Region selection should be limited to country region = ChainedForeignKey( to=Region, chained_field="country", chained_model_field="country", on_delete=models.PROTECT, null=True, blank=True, ) # City selection should be limited to region city = ChainedForeignKey( to=City, chained_field="region", chained_model_field="region", on_delete=models.PROTECT, null=True, blank=True, ) location = PointField(null=True, blank=True) This is the planned workflow: User sets the country of the site User sets the region of the site (selection is limited by country) User sets the city of the site (selection is limited by region) When the city changes, the point on the map widget for the location field jumps to the location of the city The user then fine-tunes the location manually and saves In order to achieve this, I have added this js file using the Media class in SiteAdmin: $(document).ready(function() { $("select[name='city']").change(function(e) { const cityId = e.target.value geodjango_location.clearFeatures() // Get the location of the selected city $.ajax({ "type" : "GET", "url" : `/sites/admin/city-location/${cityId}/`, "dataType" : "json", "cache" : false, "success" : function(json) { // Use the city's location as the value … -
Processing a Django form
I have a problem using Django forms while learning Django and adapting code from a variety of online courses and examples. As a result, the code may be “messy” – but if I can get it to work the way I need, I can improve my coding style later. I wish to display a template that contains a form. Some of the data displayed in the page rendered in the template is read from one table/model, polls_CC_Questions, and I wish to write data input in the page into a related table, polls_CC_Resp_NoFK. The models used are: class CC_Questions(models.Model): q_text = models.CharField('Question text', max_length=200) C1_Type = models.CharField('Choice 1 Type', max_length=2) Choice1_text = models.CharField('Choice 1 text', max_length=100) C2_Type = models.CharField('Choice 2 Type', max_length=2) Choice2_text = models.CharField('Choice 2 text', max_length=100) # def __str__(self): return self.q_text[:20] class CC_Resp_NoFK(models.Model): Person_ID = models.IntegerField() Test_date = models.DateTimeField('date test taken') Q_ID = models.IntegerField() Response_value = models.IntegerField(default=0, validators=[MaxValueValidator(100), MinValueValidator(-100)]) # def __str__(self): return self.Person_ID Now I can display the template containing valid data when I enter the url: http://localhost:8000/polls/p2vote/4/ This is processed in urls.py app_name = 'polls' urlpatterns = [ ….. …… # ex: /polls/p2vote/<q_id> path('p2vote/<int:q_id>/', p2_views.p2vote, name='p2vote'), ….. The views.py entry that is used: def p2vote(request,q_id): #next line … -
How to check if the Django-background process is running in server?
The command to start the background process is, nohup python manage.py process_tasks & Similarly in Linux which is the command used to check running status? -
Django static file images not displayed on IBM Cloud Foundry
I've read some other threads, googled, and tried reading docs but can't find what I'm looking for. I am new to playing with Django, fyi. This same code runs alright on my local and also on pythonanywhere.com My web app displays a list of 'interests', 'images', and a 'urls'. The 'image' is actually a path to the local image file. The app deploys fine to IBM Cloud Foundry and works, except that the images in static files do not display only the broken image icon displays. When I deploy, I see in the logs the message "153 static files copied to '/tmp/app/static'" which leads me to believe the collectstatic ran without issue. from models.py: class Interest(models.Model): interest = models.CharField(max_length=100) **image = models.ImageField(upload_to='interest/images')** url = models.URLField(blank=True) def __str__(self): return self.interest From the html template: {% extends 'portfolio/base.html' %} {% block about-class %} about-color-class {% endblock %} {% block content %} {% load static %} <!-- Interests --> <section class="interests"> <div class="container"> <div class="row"> <h1>Some of my interests...</h1> </div> <div class="row-images"> {% for interest in interests %} <div class="col-lg-1 col-md-1 col-xs-1"> <a href="{{ interest.url }}"><**img src="{{ interest.image.url }}" alt=""**></a> </div> {% endfor %} </div> </div> </section> <!-- Interests End --> From settings.py: … -
Django REST framework - How i can unittest model serializer?
can anybody help. I really can't figure out how to test my model seriazlier. I'm using ModelViewSet. Cant find any information in google. tests where i'm trying to test serializer def test_company_serializer(self): self.user1 = User.objects.create_user( username='user1', password='password', ) self.user2 = User.objects.create_user( username='user2', password='password', ) serializer_data = CompanySerializer(self.company1, self.company2, many=True).data expected_data = [ {'name': 'test_company1', 'owner': 'user1'}, {'name': 'test_company2', 'owner': 'user2'}, ] self.assertEqual(serializer_data, expected_data) asserterror looks like this AssertionError: When a serializer is passed a `data` keyword argument you must call `.is_valid()` before attempting to access the serialized `.data` representation. You should either call `.is_valid()` first, or access `.initial_data` instead. models.py class Company(models.Model): name = models.CharField(max_length=255, unique=True, help_text='Название') owner = models.OneToOneField(User, on_delete=models.CASCADE, help_text='Владелец') created = models.DateTimeField(auto_now_add=True, help_text='дата регистрации компании') slug = models.SlugField( max_length=255, unique_for_date='created', blank=True, validators=[validate_slug] ) class Meta: ordering = ['-created'] verbose_name_plural = 'Companies' def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Company, self).save(*args, **kwargs) serializers.py class CompanySerializer(serializers.ModelSerializer): medicines = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='medicine-detail', ) owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Company fields = ( 'url', 'pk', 'name', 'owner', 'created', 'medicines', )