Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How django load cached result for django prefetch_related? I need to know for debugging it
Looks like some of my code fails to properly use a prefetched query (Using Django/Graphene), resulting in 2N+1 queries... From my understanding, when the property is accessed, django will grab that from prefetch cache if it is prefetched, or grab from DB if not prefetched. So the problem is likely that the code access the property in such a way Django thinks it's not prefetched. So the question is, how can I access the cached result for Django prefetch_related? Which code does the actual grabbing of data (executing raw SQL or get cache) in Django? Sorry if I misunderstood anything since my knowledge of Django is quite limited. -
Linking instance of a model with instance of a different model using ModelForm
I have two models, "Fixture" and "PlayerVotes". The PlayerVotes model has two foreign keys, a link to a particular fixture and the voter (request.user). I want to display the entire list of fixture as an expandable accordion (bootstrap4) and allow the logged in user to give some votes for each instance of fixture. I am not sure where I could have the form validation and the save() functions. models.py class Fixture(models.Model): season = models.PositiveIntegerField(blank=False, null=False, validators=[ MinValueValidator(2019), MaxValueValidator(datetime.now().year)]) round = models.PositiveIntegerField(blank=False, null=False) game_time = models.DateTimeField(blank=True, null=True) opponent = models.ForeignKey(Teams, on_delete=models.SET_NULL, null=True) goals_for = models.PositiveIntegerField(null=True) goals_againt = models.PositiveIntegerField(null=True) def __str__(self): return 'Round '+str(self.round)+ ' ('+str(self.season)+ ')' class PlayerVotes(models.Model): voter = models.ForeignKey(User,related_name="voter" ,on_delete=models.SET_NULL, null=True) round = models.ForeignKey(Fixture, on_delete=models.SET_NULL, null=True) three_votes = models.ForeignKey(User,related_name="three_votes" ,on_delete=models.SET_NULL, null=True) two_votes = models.ForeignKey(User,related_name="two_votes" ,on_delete=models.SET_NULL, null=True) one_vote = models.ForeignKey(User,related_name="one_vote", on_delete=models.SET_NULL, null=True) def __str__(self): return self.voter+ '('+str(self.round) + ')' forms.py class PlayerVotesForm(forms.ModelForm): class Meta: model = models.PlayerVotes fields = ('three_votes', 'two_votes', 'one_vote') def __init__(self, user, round, *args, **kwargs): self.voter = user self.round = round super(PlayerVotesForm, self).__init__(*args, **kwargs) def clean(self): all_clean_data = super().clean() three_votes = all_clean_data['three_votes'] two_votes = all_clean_data['two_votes'] one_vote = all_clean_data['one_vote'] voter = all_clean_data['voter'] if three_votes == two_votes or three_votes == one_vote or two_votes == one_vote: raise forms.ValidationError('You cannot vote … -
Charts have multiple drilldown with multiple charts in fusion charts in Python-Django
http://jsfiddle.net/fusioncharts/zdewk96j/ The above link gives u the one drill down with multiple charts on java scripts.But, I want multiple drill down(atleast three) with multiple charts on python-Django(views.py) which is render on the html. please have a look on a code which display simple chart on html In Views.py, from django.shortcuts import render from django.http import HttpResponse # Include the `fusioncharts.py` file that contains functions to embed the charts. from fusioncharts import FusionCharts from ..models import * # The `chart` function is defined to generate Column 2D chart from database. def chart(request): # Chart data is passed to the `dataSource` parameter, as dict, in the form of key-value pairs. dataSource = {} dataSource['chart'] = { "caption": "Monthly revenue for last year", "subCaption": "Harry's SuperMart", "xAxisName": "Month", "yAxisName": "Revenues (In USD)", "numberPrefix": "$", "theme": "zune" } # The data for the chart should be in an array where each element of the array is a JSON object # having the `label` and `value` as key value pair. dataSource['data'] = [] # Iterate through the data in `Revenue` model and insert in to the `dataSource['data']` list. for key in Revenue.objects.all(): data = {} data['label'] = key.Month data['value'] = key.MonthlyRevenue dataSource['data'].append(data) # Create an … -
Errors appear after running selenium based webapp?
Errors appear after running selenium based webapp successfully for the first time.Then I have to restart the webapp server and then it runs fine.How can I resolve these errors? Internal Server Error: /mobile_extractor/contact Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connection.py", line 159, in _new_conn (self._dns_host, self.port), self.timeout, **extra_kw) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\util\connection.py", line 80, in create_connection raise err File "C:\Users\DELL\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\util\connection.py", line 70, in create_connection sock.connect(sa) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen chunked=chunked) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 354, in _make_request conn.request(method, url, **httplib_request_kw) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1229, in request self._send_request(method, url, body, headers, encode_chunked) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1275, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1224, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1016, in _send_output self.send(msg) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 956, in send self.connect() File "C:\Users\DELL\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connection.py", line 181, in connect conn = self._new_conn() File "C:\Users\DELL\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connection.py", line 168, in _new_conn self, "Failed to establish a new connection: %s" % e) urllib3.exceptions.NewConnectionError: : Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it -
How to connect an iot device to a django server which is in my pc?
I am working on an IoT project, where I have built my device using raspberry-Pi. Now I want send data captured by my device to my back-end server, which is a django server. Also sending data should be done real-time. I am using a GSM module to connect the device to internet. Django server is in my local pc. Can anyone suggest a method as to how to establish the connection between my raspberry Pi device and django server. Or if there are good references please tell me. Regards. -
How to overriding model in django third party app?
I want to modified django third party model. Here the original code. default_price = models.DecimalField( decimal_places=2, max_digits=7, null=True, blank=True, verbose_name=_("Default price"), ) I want to change max_digits=7 to max_digits=9. So it become like this. default_price = models.DecimalField( decimal_places=2, max_digits=9, null=True, blank=True, verbose_name=_("Default price"), ) Is it possible to modified django third party model without directly touch original third party code or fork? Thanks -
Formatting model.DateTimeField in a dataTables
I can't figure out how to format the datetime that I'm getting out of Django models.DateTimeField. The output of the data is: 2019-04-10T21:23:47-05:00. I have tried using: columnDefs: [ { targets: 1, "width": "20%", render: $.fn.dataTable.render.moment( 'YYYY-MM-DDTHH:mm:ss-hh:mm' 'Do MMM YYYYY' ) } ], It's not working. Without the render, the row displays fine, but with the date timestamp as it is above. But once I had the render, the row doesn't display. -
@csrf_exempt not allowing Angular to send post to Django
I am trying to attach my Angular front end to my Django backend. To do this I have created my own source of session control. I have added this to my view... from django.views.decorators.csrf import csrf_exempt @require_POST @csrf_exempt def my_view_function(request): # do something I have this code on my actual server, and I am hosting Angular locally. When I submit a request I get this error in the google chrome console: Access to XMLHttpRequest at 'https://fake_real_url/signin/checkemail/' from origin 'https://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. And the apache server log says Forbidden (CSRF cookie not set.): /signin/checkemail/ I thought that csrf_exempt would fix this issue? Am I missing something? -
Django add/edit form not returning initial/default value set while initialisation
I have view which I use for both adding and editing a modelform. Edit form works fine but while loading the add form, the initial values which I had set through Python code is not showing. Views.py(1): def tracker_edit(request, track_id=None, template_name='posts/tracker_edit.html'): if track_id is not None: track = get_object_or_404(Post, pk=track_id) else: track = Post() tracker = CreateArticle(request.POST or None, instance=track) if request.POST and tracker.is_valid(): tracker.save() redirect_url = reverse('posts:tracker_list') return redirect(redirect_url) return render(request, template_name, { 'tracker': tracker }) Forms.py: Day_Of_Week=(('Weekday','Weekday'),('Weekend','Weekend')) weekno = datetime.datetime.today().weekday() if weekno<5: x = ("Weekday") else: x = ("Weekend") Day_Of_Week = forms.ChoiceField(choices=Day_Of_Week, widget=forms.RadioSelect, initial=x) For example, from the forms.py you can see I'm expecting the radio button to be auto selected as weekday or weekend. But none is selected. Im confused, am I doing anything wrong with get/put? Any fix for the above will be appreciated.. -
django raw query return non-ordered dict position according to select query
I have a query, for example select a, b, c, d from table. why does the dict return sometimes [{'b': 2}, {'a': 1}, {'d': 4}] ....] etc. I want it [{'a': 1}, {'b': 2}, {'c': 3}, ....] according to the position in the select query. db.execute(query) data = dictfetchall(db) def dictfetchall(cursor): # Return all rows from a cursor as a dict columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] -
405 error on submitting a modelform using class based views
I created a ModelForm which renders correctly and displayed but whenever i try to submit the form I get a 405 error and the page doesnt redirect to success page. Ive gone through the django 2.2 documentation trying many different things but nothing seems to work My code is configured as such the template: <form enctype="multipart/form-data" action="{% url 'order_thanks' %}" method="post" novalidate> {% csrf_token %} {{ form|crispy }} <input name="Submit" type="submit" class="btn btn-success" value="Git my food!"></input> The model: from django.db import models from django.forms import ModelForm, Textarea, Select, CheckboxSelectMultiple, CheckboxSelectMultiple from django import forms BURGER_CHOICES = (("AFBB", "Aurion's Famous Beef Burger"), ("AIPB", "Aurion's Infamous Pork Burger"), ("AULB", "Aurion's Undiscovered Lamb Burger"), ("POG", "Pureed Otter Giblets")) BUN_CHOICES = (("WHITE","White Bread"), ("RYE","Rye"), ("TPOODLE", "Teacup Poodles"), ("AFOSSIL","Ammonite Fossils")) TOPPING_CHOICES = (("CHEESE", "Cheese"), ("LETTUCE", "Lettuce"), ("TOMATOE", "Tomatoe"), ("ONION", "Onion"), ("WSHAVE", "Wood Shavings")) SAUCES_CHOICES = (("OZTS", "Our Zesty Barbaque Sauce"), ("SEZBS", "Someone Elses Zesty Barbaque Sauce"), ("VS", "Varmint Squeezings")) EXTRAS_CHOICES = (("P", "Pinapple"), ("SG", "Soylent Green"), ("SB", "Soylent Blue"), ("MWS", "More Wood Shavings")) class Order(models.Model): burger = models.CharField(max_length=50,choices=BURGER_CHOICES ) bun = models.CharField(max_length=50, choices=BUN_CHOICES) toppings = models.CharField(max_length=60, choices=TOPPING_CHOICES) sauces = models.CharField(max_length=60, choices=SAUCES_CHOICES) extras = models.CharField(max_length=60, choices=EXTRAS_CHOICES) # def get_absolute_url(self): # return reverse('burger', kwargs={'pk': self.pk}) def __str__(self): … -
Django, Forbidden (CSRF cookie not set.) How to catch when a form submitted and redirect to GET
How do you control over CSRF token error when a client submits the form with POST and if CSRF token error occurs, I'd like to redirect the client to def get which has a form. I found only CSRF_FAILURE_VIEW can be set to an error page but there is nothing I can control over redirection for CSRF error. When the error occurs, Django make an internal server error. So I cannot catch the error in the view. -
Django templates accessing dictionary from another dictionary key
I'm iterating a dictionary, then trying to access another dictionary from a value inside of the previous dictionary. Example: {% for choice in choices %} {{ percentages[choice.id] }} {% endfor %} As in: for choice in choices: percentages[choice.id] Though I get an error: Could not parse the remainder: '[choice.id]' from 'percentages[choice.id]' Which I thought may work. I tried researching and changing [choice.id] into |get:choice.id, but that also gave me an error. -
Two forms in Django- how to make form submittable without all fields full?
I have two forms in one view. I want to be able to submit one form WITHOUT filling out the other. I have figured out how to process the forms seperately by having a different action for each form, but I am using django ModelForms and all fields need to be filled before either form can be submitted. I have tried making the fields optional but it does not work for my use, I need all the fields in each form to be filled out in order to be submitted. Here is my HTML: <form method="post" action="successfulpost" class="form-inline"> {% csrf_token %} {{applicantform}} <input type="submit" class="btn btn-primary" value="View full posting"></input> </div> And my form code: class ApplicantForm(forms.ModelForm): first_name = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'First name'}), label='') last_name = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Last name'}), label='') referrer = forms.ModelChoiceField(queryset=Referral.objects.all()) class Meta: model = Applicant fields = ('first_name', 'last_name', 'referrer') Is this possible to do- maybe not possible with ModelForms? -
NameError: name 'InMemoryUploadedFile' is not defined
I am getting NameError: name 'InMemoryUploadedFile' is not defined and s o it is a class I have done something like this djano.core.files.uploadedfile import InMemoryUploadedFile but still getting error.... I copied that code from here how to compress the image before uploading to s3 in django? my code in #models.py class Org(models.Model): name = models.TextField(verbose_name='Name of Organisation') logo = models.ImageField(upload_to='org_logos', blank=True, null=True) share_google_url = models.TextField(verbose_name="Google Business Link", blank=True, null=True) sharing_destinations = models.ForeignKey(SharingDestination, on_delete=models.CASCADE, null=True, blank=True) sms_counter = models.IntegerField(default=0) email_counter = models.IntegerField(default=0) def __str__(self): return f'{self.name}' def save(self): # Opening the uploaded image im = Image.open(self.logo) output = BytesIO() # Resize/modify the image im = im.resize((100, 100)) # after modifications, save it to the output im.save(output, format='JPEG', quality=90) output.seek(0) # change the imagefield value to be the newley modifed image value self.logo = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.logo.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super(Org, self).save() -
How to fix AssertionError 200!=302
I got a registration view that registers new users, logs them in and then redirects them to home page. When I am testing this view using unittest I am getting an AssertionError 200!=302 views.py : def register(request): if request.method =='POST': form = RegistrationForm(request.POST) if form.is_valid(): user=form.save() username = request.POST.get('username') password = request.POST.get('password1') login(request, user) return redirect(reverse('home:home')) else: form = RegistrationForm() args = {'form': form} return render(request, 'accounts/reg_form.html', args) test_views.py: class TestViews(TestCase): def setUp(self): self.client = Client() self.burial=User.objects.create_user( username='burial', password='secret' ) def test_registration_view(self): url = reverse('accounts:register') response = self.client.post(url, { 'username': self.burial.username, 'password': self.burial.password }) self.client.login(username=self.burial.username, password=self.burial.password) self.assertEquals(self.burial.username, 'burial') self.assertEquals(response.status_code, 302) I am getting AssertionError 200!=302 Thank you for any help. -
How to represent a US state in my Django model?
I'm using Django, Python 3.7. I want to represent a US state field in my model. So I added this from django.contrib.localflavor.us.models import USStateField ... class UsLocation(models.Model): address_1 = models.CharField(_("address"), max_length=128) address_2 = models.CharField(_("address cont'd"), max_length=128, blank=True) city = models.CharField(_("city"), max_length=64, null=False) state = USStateField(_("state"), null=False) zip_code = models.CharField(_("zip code"), max_length=10, null=False) Bu tthis is resulting in an "Unresolved reference 'USStateField'" in the import line. I'm not tied to using this library. Is there another way I can conveniently represent a US state and if not, what's wrong with the above? -
Django Rest - TemplateDoesNotExist: How to solve it?
Before anyone asks, I've checked a lot of answers, and 'rest_framework' is listed on my Installed Apps. I have created a new venv and installed all dependencies on it again and still the same error. When I try the url http://127.0.0.1:8000/admin I get the error template TemplateDoesNotExist at /Admin. When I try any endpoint of my API I get the same error. I'm a bit confused because this project was running on my computer 1 month ago, but I got a problem in my computer and had to format. When I cloned the project again, got this error. I'm going to list some of my settings about directory folder, I'm having a bad feeling about it. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static'), ] Folders structure is: Appapi/ movies/ settings.py urls.py wsgi.py imdb/ migrations/ migrationsfiles.... models.py views.py serializers.py ... venv/ manage.py README.md requirements.txt And some other files, like gitignore, procfile, etc. Some of the errors traceback: django.template.exceptions.TemplateDoesNotExist: index.html line 47, in select_template raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) -
design django model for real estate
i have build a real estate management system with django , i want to know if my design databse was wrong , please let me know to improve it class Profile(models.Model): user = models.OneToOneField(User , on_delete=models.CASCADE) name = models.CharField(max_length=50 ) image = models.ImageField(upload_to='profiles' , default='logo.png') phone = models.CharField(max_length=11 , default='') bio = models.CharField(max_length=100 , default='') city = models.CharField(max_length=20, default='erbil') location = models.CharField(max_length=40,default='') date = models.DateTimeField(default=datetime.now) active = models.BooleanField(default=False) def __str__(self): return f'{self.user}' class Listing(models.Model): objects = ListingManager() company = models.ForeignKey(User , on_delete=models.CASCADE ) title = models.CharField(max_length=200) slug = models.SlugField(unique=True , default='',blank=True) address = models.CharField(max_length=200) city = models.CharField(max_length=100,choices=city_choices , default='lodon' ) estate_type = models.CharField(max_length=20,choices=estate_choices, default=house) description = models.TextField(blank=True) rent_sale = models.CharField(max_length=20, choices=rent_sale_choice , default=sale) price = models.IntegerField() bedrooms = models.IntegerField(default=0) bathrooms = models.DecimalField(max_digits=2, decimal_places=1) garage = models.IntegerField(default=0 ) sqft = models.IntegerField() sold = models.BooleanField(default=False) sold_time = models.DateTimeField(default=datetime.now,blank=True) photo_main = models.ImageField(upload_to='listings_main') photo_1 = models.ImageField(upload_to='listings_1', blank=True) photo_2 = models.ImageField(upload_to='listings_1', blank=True) photo_3 = models.ImageField(upload_to='listings_1', blank=True) photo_4 = models.ImageField(upload_to='listings_1', blank=True) photo_5 = models.ImageField(upload_to='listings_1', blank=True) photo_6 = models.ImageField(upload_to='listings_1', blank=True) is_published = models.BooleanField(default=True) list_date = models.DateTimeField(default=datetime.now, blank=True) unless = models.CharField(default='',max_length=20) should i change the code or not ? if yes where should will be changed ? or make the models for more than two tables (classes) -
django-rest-auth password reset sending wrong domain in email
I'm trying to test my password reset configuration on my localhost using django-rest-auth. The email verification and registration work, and I can trigger a password reset event and send an email, but the email contains the wrong domain. Right now it is passing a link containing my-site.com as the domain instead of 0.0.0.0:8000 as the domain. I am running the app inside a docker container which is why it is 0.0.0.0:8000 instead of 127.0.0.1:8000. Current result: You're receiving this email because you requested a password reset for your user account at My Site. Please go to the following page and choose a new password: http://my-site.com/auth/password-reset/confirm/OA/55d-7dc2614593146ac3ce82/ Your username, in case you've forgotten: testaccount Thanks for using our site! The My Site team Expected result You're receiving this email because you requested a password reset for your user account at My Site. Please go to the following page and choose a new password: http://0.0.0.0:8000/auth/password-reset/confirm/OA/55d-7dc2614593146ac3ce82/ Your username, in case you've forgotten: testaccount Thanks for using our site! The My Site team My url file for my registration is: from django.urls import path, include from allauth.account.views import ConfirmEmailView from . import views urlpatterns = [ path('registration/account-email-verification-sent/', views.null_view, name='account_email_verification_sent'), path('registration/account-confirm-email/<key>', ConfirmEmailView.as_view(), name='account_confirm_email'), path('registration/complete/', views.complete_view, name='account_confirm_complete'), … -
How can I use my python app using WIndows?
I have one python app which use the following modules : - matplotlib - tkinter - pylab - numpy - ... This python app works perfectly with Linux but I would like to use this using Windows. I saw there is some modules which allows to compile my python code but I try and I get some errors. That is why I thought to two things : Using something like docker with Windows and then install Linux on Docker and use my python app but my python app use Tkinter and I thought docker works only with terminal there is no GUI Using a website to put my python code on the web and then allow to use my python code with any OS. I thought to do this using Django but I don't know if I could do this and mostly if it will work. Could you help me please ? Thank you very much. -
Import data from a text file into a pandas dataframe
I'm building a web app using Django. I uploaded a text file using csv_file = request.FILES['file']. I can't read the csv into pandas. The file that i'm trying to import has text and data, but I only want the data. I've tried the following df = pd.read_csv(csv_file, sep=" ", header=None, names=["col1","col2","col3"], skiprows = 2) to try to remove the comments and just read the numbers Error: pandas will not read all 3 columns. It only reads 1 column I tried df = pd.read_csv(csv_file, sep="\s{2}", sep=" ", header=None, names=["col1","col2","col3"], skiprows = 2) to try to remove the comments and just read the numbers Error: cannot use a string pattern on a bytes-like object I tried df = pd.read_csv(csv_file.read(), sep=" ", header=None, names=["col1","col2","col3"], skiprows = 2) to try to remove the comments and just read the numbers File I uploaded % filename % username 2.0000 117.441 -0.430 2.0100 117.499 -0.337 2.0200 117.557 -0.246 2.0300 117.615 -0.157 2.0400 117.672 -0.069 views.py def new_measurement(request, pk): material = Material.objects.get(pk=pk) if request.method == 'POST': form = NewTopicForm(request.POST) if form.is_valid(): topic = form.save(commit=False) topic.material = material topic.message=form.cleaned_data.get('message') csv_file = request.FILES['file'] df = genDataFrame(csv_file) topic.data = df topic.created_by = request.user topic.save() return redirect('topic_detail', pk = material.pk) else: form … -
How do I solve "django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library" when running PyCharm test?
I'm using Django, Python 3.7. and PyCharm 2018.3.5. I have this test file ... ./web/tests/view_tests.py It looks like the below # Basic test to verify we can get valid return data def test_calculate_tax(self): state = 'MN' gross = 100000 salary = 75000 json_data = json.dumps({'state': state, 'gross': gross, 'salary': salary}) response = c.post('/content/vote/', json_data, content_type='application/json', HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 302) # this is OK. print(response.content) self.assertEqual(response.content, 2) When I right click the test name in PyCharm and select the "Run Test" option, though, I get the below error. I have no idea what it means or how to fix it ... Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_test_manage.py", line 56, in <module> django.setup() File "/Users/davea/Documents/workspace/myproject/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/davea/Documents/workspace/myproject/venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/davea/Documents/workspace/myproject/venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/davea/Documents/workspace/myproject/web/models.py", line 2, in <module> from django.contrib.gis.db import models File "/Users/davea/Documents/workspace/myproject/venv/lib/python3.7/site-packages/django/contrib/gis/db/models/__init__.py", line 3, … -
Urlize DRF Link
I have a DRF serializer: class ActivitySerializer(serializers.ModelSerializer): link = serializers.CharField(source='get_analytic_link', allow_null=True) class Meta: model = Activity fields = ['link',] In the browsable API, the links are clickable. However, when they are served up to a DataTable via a JSON endpoint, they are (predictably) not clickable. In plain Django, I would do something like this: <td>{{ activity.get_analytic_link|urlize }}</td> How could I replicate that behavior in DRF so that links are clickable? -
How to run a method inside a Model when a JavaScript actionListener is triggered?
I have the next Model: class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length = 200) text = models.TextField() created_date = models.DateTimeField(default = timezone.now) likes = models.IntegerField(default=0) tags = models.CharField(max_length = 50, default = '' ) def process_likes(self): like = self.likes = F('likes')+1 like.save() def split_tags(self): return self.tags.split() def get_absolute_url(self): return reverse('blog:post_list') def __str__(self): return self.title What I want to do is when a icon in a template is clicked, I want the process_likes method to be run, this method is going to increment by one the value of likes. My script looks like this: <script> let corazon = document.querySelector('.icon-heart-empty'); corazon.addEventListener('click', ()=>{ corazon.classList.toggle('icon-heart'); }); </script> Here I toggle the class of my icon to show if is clicked or uncliked, but how can I call the process_like method using pure JavaScript?