Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Test Not Getting Model Object
I am just scratching the surface of testing in Django. Here is my testing code, inside tests.py: class AdvertisingTests( TestCase ): def test_get_ad( self ): ''' Test if the get ad feature is working, should always load an ad ''' url = reverse('advertising:get_ad') response = self.client.get( url ) self.assertEqual(response.status_code, 200) This test is just a basic test of a view that should return an Ad. Here is the view code: from .models import Ad, Impression def get_ad(request): FirstAd = Ad.objects.first() # +1 impression Impression.objects.create(ad = FirstAd) import json data = { 'url': FirstAd.url, 'image_url': FirstAd.image.url, 'title': FirstAd.title, 'desc': FirstAd.desc } json_data = json.dumps( data ) return HttpResponse(json_data, content_type='application/json') I am working in a heroku local environment, so I run the tests like this: heroku local:run python manage.py test advertising And this test fails, coming from the Impression.objects.create(ad = FirstAd) line: ValueError: Cannot assign None: "Impression.ad" does not allow null values. What that tells me is that the FirstAd object is null. OK so I wind up the local shell like this: heroku local:run python manage.py shell to double check. Replicating that code there are no errors: In [2]: from advertising.models import Ad, Impression In [3]: print Ad.objects.first() Flamingo T-Shirt Corporation … -
Django dinamically add forms to inline formsets
In my application i made an inline formset where the user can select multiple languages. In order to make this dynamic i tried to make a javascript function where he can press an 'add' button and another form would appear. Sadly i couldn't make it done, I've tried other examples from stack, but i couldn't make it work for my formset. views.py @login_required() def translator_data(request): data = dict() if request.method == "POST": t = get_object_or_404(Translator, user=request.user) form = TranslatorForm(request.POST, request.FILES, instance=t) formset = TranslatorFormSet(request.POST) if form.is_valid(): translator = form.save(commit=False) formset = TranslatorFormSet(request.POST, instance=translator) if formset.is_valid(): translator.user = request.user translator.save() for form in formset.forms: form.save() return redirect(reverse_lazy('translator:translator_test')) else: t = get_object_or_404(Translator, user=request.user) form = TranslatorForm(instance=t) formset = TranslatorFormSet() data['formset'] = formset data['form'] = form data['checkbox_fields'] = ['available_monday', 'available_tuesday', 'available_wednesday', 'available_thursday', 'available_friday', 'available_saturday', 'available_sunday'] data['formset_fields'] = ['language', 'type', 'experience'] return render(request, 'translator/data_middleware.html', data) forms.py class TranslatorDataForm(ModelForm): class Meta: model = TranslatorData fields = ['language', 'type', 'experience'] exclude = ['translator', 'id', 'delete'] labels = { 'language': _('Limbă'), 'type': _('Tip'), 'experience': _('Experiență'), } def __init__(self, *args, **kwargs): super(TranslatorDataForm, self).__init__(*args, **kwargs) self.fields['language'].widget.attrs.update({'class': 'form-control m-bootstrap-select m_selectpicker', 'required': True}) self.fields['type'].widget.attrs.update({'class': 'form-control m-input', 'id': 'exampleSelect2', 'required': True}) self.fields['experience'].widget.attrs.update({'class': 'form-control m-bootstrap-select m_selectpicker', 'required': True}) TranslatorFormSet = inlineformset_factory(Translator, TranslatorData, form=TranslatorDataForm, … -
graphene relation using RESTfull API as data source
I'm using django graphene for building a graphql server, it consume a RESTfull API to get data, following this schema: class DeviceType(graphene.ObjectType): id = graphene.ID() reference = graphene.String() serial = graphene.Float() class InstallationType(graphene.ObjectType): id = graphene.ID() company = graphene.Int() device = graphene.ID() class AllDataType(graphene.ObjectType): device = graphene.Field(DeviceType) installation = graphene.Field(InstallationType) class Query(graphene.ObjectType): installation = graphene.Field( InstallationType, device_id=graphene.Int(required=True) ) all = graphene.Field( AllDataType, serial=graphene.Float(required=True) ) def resolve_installation(self, info, device_id): response = api_call('installations/?device=%s' % device_id)['results'][0] return json2obj(json.dumps(response)) def resolve_all(self, info, serial): response = api_call('devices/?serial=%s' % serial)['results'][0] return json2obj(json.dumps(response)) The query I need to do is like this: query { all(serial:201002000856){ device{ id serial reference } installation{ company device } } } So, my problem is how to make a relation with this two types, as described in AllDataType, the resolve_installation needs a device id and resolve_all needs a serial number of device. To resolve the installation I need the device id returned by resolve_all resolver. How can I achieve this? -
Tracking a Google Analytics Conversion Event
I have a website running on the Django framework and I need to incorporate Google Conversion Tracking onto the page that tracks clicks when the user clicks on an link. My current setup for links uses Django template language like so: <a href="{% url 'redirect_click' argument1 argument2 .... %}" target="_blank"> The problem is the Django URL used by the link. When a user clicks it, a view is called in the Django framework that logs details about the click and then redirects them to the links page. I've tried fiddling with the sample Google Tracking code here but I do not know how to modify it to wait until the redirect finishes before checking for the google_trackConversion variable on the page its redirected to: <!-- Google Code for Add to Cart Conversion Page In your html page, add the snippet and call goog_report_conversion when someone clicks on the chosen link or button. --> <script type="text/javascript"> /* <![CDATA[ */ goog_snippet_vars = function() { var w = window; w.google_conversion_id = 12345678; w.google_conversion_label = "abcDeFGHIJklmN0PQ"; w.google_conversion_value = 13.00; w.google_conversion_currency = "USD"; w.google_remarketing_only = false; } // DO NOT CHANGE THE CODE BELOW. goog_report_conversion = function(url) { goog_snippet_vars(); window.google_conversion_format = "3"; var opt = … -
Heroku, Django. Automatically delete record in db after sertain time
I want that old record in db are deleted automatically. Iam trying to set something like scheduler or apscheduler on my heroku server but it not seems to be worked. What i did was create management command for heroku scheduler (import django; django.setup() is needed to fix settings error): ` import django django.setup() from django.core.management.base import BaseCommand, CommandError from shortener.models import ShortURL from datetime import datetime, timedelta from django.utils import timezone from url_shortener.settings import SHORT_URL_LIFE_TIME class Command(BaseCommand): help = 'Delete short-url record in db older than {0} day(s)'.format(SHORT_URL_LIFE_TIME) def handle(self, *args, **options): # ShortURL.objects.filter(creation_date__lte=timezone.now() - timedelta(days=SHORT_URL_LIFE_TIME)).delete() ShortURL.objects.filter(creation_date__lte=timezone.now() - timedelta(minutes=1)).delete()` This command successuffly deletes record in local server but in heroku it doesnt. I also tried set clock-processes with setting clock.py as: `import django django.setup() from apscheduler.schedulers.blocking import BlockingScheduler from shortener.models import ShortURL from datetime import datetime, timedelta from django.utils import timezone # from url_shortener.settings import SHORT_URL_LIFE_TIME sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def timed_job(): ShortURL.objects.filter(creation_date__lte=timezone.now()-timedelta(minutes=1)).delete() sched.start()` But it's not working either. -
to edit queryset in python django
total_trans_today = Addfuel.objects\ .filter(date_created__year=datetime.today().date().year, date_created__month=datetime.today().date().month, date_created__day=datetime.today().date().day) In above queryset, it gives data for today or day wise, how do i edit it to get data for month or month wise. Please help -
CRSF incorrect to Django from AJAX
I Know this is a common problem but after tring every web solution, I still got "CSRF token missing or incorrect." error. The ajax call use correctly the cookie crsf token DJango has created using on the the common csrf solution: beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", window.csrftoken); } } This is the POST header: Accept:*/* Accept-Encoding:gzip, deflate, br Accept-Language:it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7,es;q=0.6 Connection:keep-alive Content-Length:31 Content-Type:application/x-www-form-urlencoded; charset=UTF-8 Cookie:csrftoken=PV730Sh7PhMM4WKlnSmzMv726Y5wspf4LKHz8XR9TfHVeY167a8aAzbU8Oci6VMf Host:127.0.0.1:8000 Origin:http://localhost:3000 Referer:http://localhost:3000/ User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 X-CSRFToken:uD3NP6tHllrSSnx4qi23EVgIZy0dkVE5qhZCYN5A9ZETI8SITPb0NGtamIezFTPv In DJANGO, im using the middleware: 'django.middleware.csrf.CsrfViewMiddleware', Django View doens't have any @csrf option because is an authenticate POST. As you see from headers, my Ajax Call start from another "port" (a React Application). For development, i have disabled in Chrome the cross-origin check to ensure my call goes normally. This is a piece of Django view: def login(request, *args, **kwargs): username = request.POST['username'] password = request.POST['password'] c = {} try: user = authenticate(request,username=username, password=password) if user is not None: return JsonResponse(user.id, safe=False, status=200) Im worried about the headers. As you can see, the X-CSRFToken (created by Django after a first GET call with the option @ensure_csrf_cookie) is different from Cookie:csrftoken= which value I don't know … -
Django 2 static files
I know this has been ask about a million times, but just don't get djangos static file handling. In prod I will deploy in s3 wich already works nicely. But in dev (local running) not so much. Problem 1: If I set the config to this: if ENVIRONMENT == "dev": BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] I can not run collectstatic as of the following error: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. OK, makes sense, so I configure it to the following Problem 2: if ENVIRONMENT == "dev": BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Now I can run collectstatic. But if run the server it will not find the static files: "GET /static/css/bootstrap.min.css HTTP/1.1" 404 What I dont't get: The Problem 1 can server the static files, which Problem 2 collects... How do I configure Django 2 to simply collect and server static files within one simple 'static' folder within the root of my project? -
django FileField and data migrations
So I added a FileField to my model: def sig_directory_path(instance, filename): try: ext = filename.split('.')[-1] except: ext = "" filename = '{}.{}'.format(uuid4().hex, ext) return 'sig/{0}'.format(filename) ServiceReportData(models.Model): ... # Newly added. ca_technicianSignatureImage = models.FileField(null=True, blank=True, verbose_name="Technician Signature", upload_to=sig_directory_path) I already created the auto migration and migrated the changes. So the DB now has null values for ca_technicianSignatureImage column. Then I wanted to create a data migration for this field because I don't want null values for the field: from django.core.files.base import ContentFile from django.db import migrations # File content. no_image_svg_content = """ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="200" height="150"> <rect width="199" height="149" x="0.5" y="0.5" id="rect2824" fill="#ffffff" stroke="#999999" stroke-width="1"/> <text x="64.648438" y="79.863152" id="text2818" font-size="24" font-weight="bold" text-align="center" text-anchor="middle" fill="#999999" stroke="none" font-family="Sans"> <tspan x="100" y="60" id="tspan2820">No image</tspan> <tspan x="100" y="90" id="tspan2822">available</tspan> </text> </svg> """ def set_signatures(apps, schema_editor): no_image_data = ContentFile(no_image_svg_content) ServiceReportData = apps.get_model('mism', 'ServiceReportData') for service_report in ServiceReportData.objects.all(): if service_report.ca_customerSignatureImage is None: service_report.ca_customerSignatureImage.save('no_image.svg', no_image_data) class Migration(migrations.Migration): dependencies = [ ('mism', '0004_auto_20180131_1651'), ] operations = [ migrations.RunPython(set_signatures, migrations.RunPython.noop), ] Running this migration doesn't change the DB. I can't figure out how to do it. Simply, I just want to put a default .svg file in the field if the field is empty. How … -
Django widget form for get_or_create
I have a Select widget but I need list all of values about a fielf of Model, and create new values of these field at the same input. With select I can list and choose one value, but can't create news. Whith textinput I can create but not list. What widget form can I use? -
git pull origin master returns "Already up-to-date" even though it isn't
I'm using git pull origin master to pull my Bitbucket repo onto my Digital Ocean Django server directory (which already has some folders for Django like env and static) . When I do this it says Already up-to-date. but the repo didn't come through? I'm not sure if I'm misinterpreting what git pull does but I assumed it took the contents of mu repo and merged with my current directory. If this isn't true, can somebody explain what other command I should do to achieve this? -
How do keyword arguments interact with model? Django
I have a question regarding the models in Django, specifically regarding how the attributes one specifies, such as: "author = models.CharField...", connect to the keyword arguments that are passed when creating instances of those same models. A typical model that I am reading about can look like: from django.db import models class MyModel(models.Model): Attribute = models.CharField(max_length=100) Then, when instantiating this and creating and object, what I see is frequently like this: Instance = MyModel(Attribute='some text') How do these connect? I know that the init in the parent class of my 'MyModel' takes kwargs - but I am not sure how it deals with them. How does Django make sure they connect to the Attribute that I have written? It kind of seems like I define an attribute in the model, and then try to redefine that same attribute when instantiating? Thanks! -
Unable to use helper class with pytests
Helper Class class UserBuilder: def __init__(self): self.user = CustomUser.objects.get(email='random_email@test.com') def get_user(self): return self.user Testing Class @pytest.mark.django_db @pytest.mark.parametrize('(user, output)', [ (user_builder.change_bank_billdesk_bank_id(bank_name="IDN").get_user(), -1), (user_builder.change_bank_billdesk_bank_id(bank_name="IDB").get_user(), -1), (user_builder.change_bank_billdesk_bank_id(bank_name="SBI").get_user(), 1) ]) def test_users_with_different_banks(self, user, output): Error Log tests/trial.py:16: in <module> @pytest.mark.django_db tests/trial.py:100: in TestFunction user_builder = UserBuilder() tests/builder/user_builder.py:13: in __init__ self.user = CustomUser.objects.get(email='random_email@test.com') ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/models/manager.py:127: in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/models/query.py:328: in get num = len(clone) ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/models/query.py:144: in __len__ self._fetch_all() ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/models/query.py:965: in _fetch_all self._result_cache = list(self.iterator()) ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/models/query.py:238: in iterator results = compiler.execute_sql() ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py:838: in execute_sql cursor = self.connection.cursor() ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/backends/base/base.py:162: in cursor cursor = self.make_debug_cursor(self._cursor()) ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/backends/base/base.py:135: in _cursor self.ensure_connection() E Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. There was no proper solution available over the internet, so I tried whatever I came across. I am unable to resolve this error. Any help would be appreciated. Thanks -
How to loop through csv file in Python/Django
I created a management command and there I want to download the csv file from ftp and update the database if necessary. The code that I have is as follows: class Command(BaseCommand): @staticmethod def update_database(row): code = row['CODE'] vat_number = row['BTWNR'] if code != "" and vat_number != "": # pdb.set_trace() print("Code: {0} --- BTW: {1}").format(code, vat_number) def read_file(self): path_to_relations_csv_file = "{0}/{1}".format(destination, file_name) with open(path_to_relations_csv_file) as csvfile: relations_reader = csv.DictReader(csvfile, delimiter=';') for row in relations_reader: self.update_database(row) def handle(self, *args, **options): # Open ftp connection ftp = ftplib.FTP(ftp_host, ftp_username, ftp_password) try: ftp.cwd(source) # Goes to remote folder where the relations file is os.chdir(destination) # Goes to local folder where the relations file will be downloaded print("Switched to the directory successful. Current directory: {}".format(destination)) except OSError: pass except ftplib.error_perm: print("Error: could not change to {0}".format(source)) sys.exit("Ending Application") try: # Get the file relations = open(file_name, "wb") # Opens the remote file ftp.retrbinary('RETR {0}'.format(file_name), relations.write) # Writes to the local file print("File {0} downloaded successfully.".format(file_name)) relations.close() # Closes the local file print("Local file closed.") ftp.quit() # Closes the ftp connection print("FTP Connection quited.") try: self.read_file() except: print("Error: Unable to read the file.") except: print("Error: File {0} could not be downloaded.".format(file_name)) But in read_file … -
Drop down lists not populating in DB in Django Forms on click of submit button
I have a table inside form. It looks like below: {% extends "base.html" %} {% block title %}Title{% endblock title %} {% block content %} <form actions="" method="post"> {% csrf_token %} <table> <table border = "1" cellpadding = "10" cellspacing = "10" bordercolor = "green"> <tr> <th>numbers</th> <th>Extension</th> <th>Vendor</th> </tr> {% for number in numbers %} <tr> <td>{{ number }}</td> <td class = "select">Select Extension <select name="extensions"> {% for obj in sipextensionsets %} <option value={{obj.sip_extension}}>{{ obj.sip_extension }}</option> {% endfor %} </select> </td> <td>vendor</td> </tr> {% endfor %} </table> <input type="submit" value="save"/> </form> {% endblock content %} My forms.py is below: from django import forms from .models import column class didsForm(forms.ModelForm): class Meta: model = column fields = ('extension') My views.py is below def saveintodb(request): try: instance = coloumn.objects.get(pk=1) except: instance = coloumn(pk=1) instance.save() if request.method == 'POST': dids_form = didsForm(data=request.POST['extensions'], instance=instance) if dids_form.is_valid(): dids_form.save() messages.success(request, "Settings updated. Please apply settings.") else: messages.error(request, "Error: Invalid settings.") else: dids_form = didsForm(instance=instance) return render(request, 'dids/index.html', {'dids_form': dids_form}) In the table, there is a drop down(select tag). I want to save the data into database when user selects something from dropdown and clicks on save button. I know I have mistaken somewhere in views … -
Add extra column to tables in django_tables2
I want to add extra-column which is not in my model. And I apply one of the solutions at this site to my project. But it doesn't work properly. model.py class Companies(models.Model): legal_name = models.CharField(max_length=120, blank=True) co_name = models.CharField(max_length=120, blank=True) client = models.ForeignKey(Clients, models.SET_NULL, blank=True, null=True) tel_no = models.CharField(max_length=120, blank=True) email = models.EmailField(null=True, blank=True) address = models.TextField(null=True, blank=True) contact = models.CharField(max_length=250, blank=True) con_tel_no = models.CharField(max_length=120, blank=True) entity = models.CharField(max_length=2, null=True) yearend = models.DateField(null=True, blank=True) bn = models.CharField(max_length=9) memo = models.TextField(null=True, blank=True) slug = models.SlugField(null=True, blank=True) def t2_due_date(self): now_year = datetime.date.today().year if self.entity == 'CO': yearend_ = DateWidget.decompress(self, self.yearend) if yearend_[1] > 6: yearend_[2] = now_year + 1 yearend_[1] -= 6 else: yearend_[2] = now_year yearend_[1] += 6 t2_due = DateWidget.compress(self, yearend_) return t2_due tables.py class ScheduleTable(tables.Table): due_date_col = tables.Column(accessor='t2_due_date', verbose_name='T2 Due Date') class Meta: attrs = {"class": "paleblue", "width":"100%"} fields = ['client','legal_name', 'co_name', 'entity', 'yearend', 'due_date_col'] model = Companies When I run this program 'due_date_col' is always blank. It seems that the function('t2_due_date) does not go through. Do you have any clue to clear this problem? -
Django - passing python data to javascript
I have a javascript code in my js.html: {% load static %} <script src="{% static "vis.js" %}"></script> <div id="mynetwork"></div> <script type="text/javascript"> var nodes = new vis.DataSet([ {'id': 1, 'label': 'node 1'}, {'id': 2, 'label': 'node 2'}, {'id': 3, 'label': 'node 3'}, {'id': 4, 'label': 'node 4'}, {'id': 5, 'label': 'node 5'} ]); var edges = new vis.DataSet([ {'from': 1, 'to': 3}, {'from': 1, 'to': 2}, {'from': 2, 'to': 4}, {'from': 2, 'to': 5}, {'from': 3, 'to': 3} ]); var container = document.getElementById('mynetwork'); var data = { nodes: nodes, edges: edges }; var options = {}; var network = new vis.Network(container, data, options); </script> I have a python variable called nodesJS which takes this form when printed: [{'id': 1, 'label': 'node 1'}, {'id': 2, 'label': 'node 2'}, {'id': 3, 'label': 'node 3'}, {'id': 4, 'label': 'node 4'}, {'id': 5, 'label': 'node 5'} ] which is the same form that this javascript would use. In my views.py i'm just passing nodesJS variable in a context. Now i wanted to write my js code in this style: var nodes = new vis.DataSet({{nodesJS}}); And the problem is that it doesn't work. Is there any way for js to treat my python variable the i … -
How to import model in Python/Django
My project structure is as follows: my_proj ---calculation ---cardata ---master ---my_proj --- __init.py__ --- admin.py --- settings.py --- url.py --- update_db_from_ftp.py ///// This is my custom file In update_db_from_ftp.py I want to download an csv file from ftp and update the database(if necessary) once every day with cron. But the problem is that I can't import model which I want to update. The model which I want to update is inside master folder in models.py file. I try to import model as follows: from master.models import ModelName But I'm getting an error as follows: Traceback (most recent call last): File "update_db_from_ftp.py", line 6, in <module> from master.models import ModelName ImportError: No module named master.models But I use the same model in cardata and calculation folder and I import it the same way as I try in update_db_from_ftp.py file, but there it works without problems. Any idea how to solve it? -
Django annotation is not working with order_by
I want to get last 100 records of MyModel order_by('-end_date') and do a SUM annotate on different winner types them MyModel.objects.all()[:100].order_by('-end_game_time').values('winner').annotate(total=Count('winner')) result query is as below and I don't have expected groups <QuerySet [{'winner': 3, 'total': 1}, {'winner': 15, 'total': 1}, 'total': 1}, {'winner': 3, 'total': 1}, {'winner': 5, 'total': 1}, {'winner': 15, 'total': 1}, {'winner': 5, 'total': 1}, {'winner': 3, 'total': 1}, '...(remaining elements truncated)...']> generated query is like SELECT "game_mymodel"."winner", COUNT("game_mymodel"."winner") AS "total" FROM "game_mymodel" GROUP BY "game_mymodel"."winner", "game_mymodel"."end_game_time" ORDER BY "game_mymodel"."end_game_time" DESC LIMIT 100 but when I don't have the order_by the result is as I expected MyModel.objects.all()[:100].values('winner').annotate(total=Count('winner')) Out[52]: <QuerySet [{'winner': 5, 'total': 43}, {'winner': 1, 'total': 2}, {'winner': 15, 'total': 51}, {'winner': 2, 'total': 42}, {'winner': 3, 'total': 43}]> and generated query group_by part is different SELECT "game_mymodel"."winner", COUNT("game_mymodel"."winner") AS "total" FROM "game_mymodel" GROUP BY "game_mymodel"."winner" LIMIT 100 -
Why calling method inside views.py after successful submission of forms doesn't clear the form?
Views.py def form_name_view(request): form = FormName() if request.method == "POST": form = FormName(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect('/') # return index(request) else: print('INVALID FORM INPUTS') return render(request, 'first_app/form_page.html', {'form': form}) When I use HttpResponseRedirect to get back to my index page, then everything works correct, but the concern is if I use calling index method instead of HttpResponseRedirect then the behavior is a little bit insane: After reaching index page if I hit refresh then alert appears says: The page that you're looking for used information that you entered. Returning to that page might cause any action you took to be repeated. Do you want to continue? If i want to get back to the same form page, by calling that same method again like return form_name_view(request) The new form is already filled with previous inserted data, with the message on the form Topic with this Topic name already exists. The question is what is the reason, calling method results like this? -
How to implement group by complex queries in django
1.UPDATE item_new JOIN (SELECT reporting_id,max(dotcom_asset_ksn) AS dksn FROM item_new GROUP BY reporting_id) b ON item_new.reporting_id = b.reporting_id SET item_new.dotcom_asset_ksn = b.dksn WHERE item_new.dotcom_asset_ksn is null and lower(bu_name)='footwear' 2.select ksn from event where event_type_id in(%s,%s) group by ksn having instr(group_concat(event_type_id),%s) > 0 and instr(group_concat(event_type_id),%s)=0 How to implement this query in django. Can anyone help me??? -
Create an universal function and abstract class for multiple apps
So I create some abstract classes in Django to override in for Model like this: import uuid from django.db import models class Identifier: @staticmethod def hex(): return uuid.uuid4().hex class Model(models.Model): class Meta: abstract = True id = models.CharField( max_length=32, unique=True, primary_key=True, default=Identifier.hex, editable=False, verbose_name='Identifier', ) created = models.DateTimeField( auto_now_add=True ) modified = models.DateTimeField( auto_now=True ) I have multiple apps at least 3 apps in my project. Should I created another app called abstracts to put every abstract classes and universal function or I put them inside the project level folder? -
Django 'WSGIRequest' object has no attribute 'data'
I am trying to do a post request to a API, and save the result into one of my database table. This is my code. This is my model. patientId is a foreign key to the userId of MyUser table class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=9, blank=True, null=True) birthday = models.DateField(blank=True, null=True) birthTime = models.TimeField(blank=True, null=True) class BookAppt(models.Model): clinicId = models.CharField(max_length=20) patientId = models.ForeignKey(MyUser, on_delete=models.CASCADE) scheduleTime = models.DateTimeField(blank=True, null=True) ticketNo = models.CharField(max_length=5) status = models.CharField(max_length=20) view.py . The api url is from another django project @csrf_exempt def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/makeapp/', data=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/makeapp/', data=request.GET) if r.status_code == 201 and request.method == 'POST': data = r.json() print(data) patient = request.data['patientId'] patientId = MyUser.objects.get(id=patient) saveget_attrs = { "patientId": patientId, "clinicId": data["clinicId"], "scheduleTime": data["created"], "ticketNo": data["ticketNo"], "status": data["status"], } saving = BookAppt.objects.create(**saveget_attrs) return HttpResponse(r.text) elif r.status_code == 200: # GET response return HttpResponse(r.json()) else: return HttpResponse(r.text) the result in the print(data) is this. [31/Jan/2018 10:21:42] "POST /api/makeapp/ HTTP/1.1" 201 139 {'id': 22, 'patientId': 4, 'clinicId': '1', 'date': '2018-07-10', 'time': '08:00 AM', 'created': '2018-01-31 01:21:42', 'ticketNo': 1, 'status': 'Booked'} But the error is here File "C:\Django project\AppImmuneMe2\customuser\views.py", line 31, in … -
Django urls help - not able to access view
Let me start by saying I'm new to Django and I realize this seems simple (and I'm hoping it is). I'm following a tutorial that is taking me through the basic set up of a simple Django site, and I've found myself stuck at a point where I'm simply calling on a new view the tutorial just had me add. (for those interested, the tutorial is here https://overiq.com/django/1.10/views-and-urlconfs-in-django/) So, I've got my server up and running, and I'm trying to access http://127.0.0.1:8000/blog/time/ When I try to access that view, I get the error: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^blog ^time/$ [name='todays_time'] ^blog ^$ [name='blog_index'] ^admin/ The current path, blog/time/, didn't match any of these. Here is the layout of my Django project: My mysite's urls.py file looks like this: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^blog/', include('blog.urls')), url(r'^admin/', admin.site.urls), ] My blog package's urls.py file looks like this: from django.conf.urls import url from blog import views urlpatterns = [ url(r'^time/$', views.today_is, name='todays_time'), url(r'^$', views.index, name='blog_index'), ] my blog package's views.py looks like this: from django.http import HttpResponse import datetime def index(request): return HttpResponse("Hello Django!!!") def … -
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 4: ordinal not in range(128)
I'm facing some trouble with Unicode. I'm a beginner in programming, so I couldn't understand the other answers related to this issue here. TraceBack Traceback: File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django/django_project/learn/views.py" in index 19. if str(get_one_phrasalverb) not in cannot_be_random: Exception Type: UnicodeEncodeError at /learn/keep-from/ Exception Value: 'ascii' codec can't encode character u'\xa0' in position 4: ordinal not in range(128) Problematic code part cannot_be_random = request.session.get('cannot_be_random') if str(get_one_phrasalverb) not in cannot_be_random: cannot_be_random.append(str(get_one_phrasalverb)) request.session['cannot_be_random'] = cannot_be_random Please tell me if some part of the code or part of the traceback is missing. Could someone help me, please?