Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Any atomic way in Django to force Postgres's AutoField sequence to be updated on explicit insertions?
While converting our monolith service to Django micro-services, we are migrating to Postgres a table of users from our old DB. The users table have a primary 'user_id' field. At first phase of our migration, we will write new users to both DB's, and will have to insert the users with explicit 'user_id' (from old DB) to the new Postgres DB. At a later phase we will stop writing to the old DB, and would like to use the auto increment ability. I know we can reset the sequence to the current MAX(user_id), the thing is we will have a time window where we'll still get explicit inserts from our old Monolith Service, and we do won't the reset to be coupled with the Monolith change. We're looking for a Django solution to support both insertion of both explicit and new generated 'user_id's, by updating the sequence on explicit insertion as well, in atomic way. Postgres seems to not support it out-of-the-box: https://code.djangoproject.com/ticket/11423 Any ideas? -
How to count executed queries during selenium test?
I've tried like this, but does not work: class SeleniumTest(LiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.driver = PhantomJS() @override_settings(DEBUG=True) def test_queries(self) with self.assertNumQueries(10): self.driver.get(self.live_server_url + "/page-with-10-queries") Output: query['sql'] for query in self.captured_queries AssertionError: 0 != 10 : 0 queries executed, 10 expected Captured queries were: -
add data attributes to <options> rendered by django form library
I have django choice field The HTML rendered by django looks like this: <select id="id_action" name="action"> <option value="" selected="selected">---</option> <option value="query-action-take">Take</option> <option value="query-action-forward">Forward</option> </select> Before executing the action which was choosen by the user, a confirmation should happen. But not all actions need a confirmation. In this example "delete" needs, but "take" does not need a confirmation. I would like to add html data attributes the options The result should look like this: <select id="id_action" name="action"> <option value="" selected="selected">---</option> <option value="query-action-take" data-need-confirm="False">Take</option> <option value="query-action-delete" data-need-confirm="True">Delete</option> </select> Up to now I found no way to inject the data "need confirmation" into individual choices. ... or am I on the wrong track here? This question is only about "how to get the data into the html". The evaluation of the data (confirmation popup) is not part of this question. -
Sign up django with cbv and AbstractUser model image error
i tried using class based views for signup but when i try to add images to the form fields, i keep getting this field is required the problem is with the image file this is the forms.py file ` from django import forms from .models import User class USerForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ['username', 'email', 'password', 'company', 'description', 'logo'] ` and the views.py file from django.shortcuts import render, redirect from django.views.generic import View, TemplateView from .forms import USerForm from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.contrib import messages from django.views.generic.edit import UpdateView # Create your views here. @login_required(login_url="/jembe/login/") def index(request): return render(request, 'base.html') class SignUp(View): form_class = USerForm template_name = 'signup.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST, request.FILES) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('invoice:index') return render(request, self.template_name, {'form': form}) class LogoutView(View): def get(self, request): logout(request) return HttpResponseRedirect('/jembe/login') class AboutView(TemplateView): template_name = "about.html" models.py file `from django.db import models from django.contrib.auth.models import AbstractUser # … -
custom django pipeline in django
I am trying to make fetch data from facebook,google and different social site using python social auth , so i want to fetch the response and use that for a model fields i have defined . here is my setting.py file :- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social.apps.django_app.default', #3rd party apps 'social_django', 'home_and_login', 'project', 'user_profile', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'project_sih.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'project_sih/templates')], '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', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.github.GithubOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.open_id.OpenIdAuth', 'social_core.backends.google.GoogleOpenId', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.google.GoogleOAuth', 'social_core.backends.twitter.TwitterOAuth', 'social_core.backends.yahoo.YahooOpenId', 'django.contrib.auth.backends.ModelBackend', '**home_and_login.pipeline.create_profile**', #this is my custom pipeline ) my models.py file to which i want to assing response data is :- class user_details(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) full_name = models.CharField(max_length=50) profile_link = models.URLField(default='/welcome_user') dob = models.DateField(null=True) #add for academic detail intro = models.CharField(max_length=200,null=True) photo_link = models.URLField(default='/static/images/anonymous-male.png') followers_total = models.IntegerField(default=0) following_total = models.IntegerField(default=0) projects_total = models.IntegerField(default=0) def __str__(self): return 'User_details: ' + self.full_name my pipeline.py file is:- from .models import user_details def create_profile(strategy, details, response, user, *args, **kwargs): print(detail) if user_details.objects.filter(user=user).exists(): pass else: name = kwargs['details']['email'] new_profile = user_details(user=user,full_name=name) new_profile.save() return … -
how can I access List type of data in django
client side, I sent a JSON data including list type data like this. $.ajax({ url: '/man/manual', type: 'POST', data: {'id':'','title':'ttt','description':'desc','steps':[{'title':'1'},{'title':'2'}]}, dataType : 'JSON', success : function(data) { console.log(data); } }); I tried to access these data. title = request.POST['title'] description = request.POST['description'] steps = request.POST['steps'] for step in steps: print(step.title) but I got an error. Traceback: File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch 89. return handler(request, *args, **kwargs) File "/Users/sangwonlee/Makewith/trunk/MW_Service/mw_manual/views.py" in post 77. self.createManual(request) File "/Users/sangwonlee/Makewith/trunk/MW_Service/mw_manual/views.py" in createManual 27. steps = request.POST['steps'] File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/utils/datastructures.py" in __getitem__ 322. raise MultiValueDictKeyError(repr(key)) Exception Type: MultiValueDictKeyError at /man/manual Exception Value: "'steps'" Request information: GET: No GET data POST: description = 'desc' steps[1][title] = '2' steps[0][title] = '1' title = 'ttt' id = '' How can I change my to code for correct data from client side. -
initial= not working on Form inputs
I have a simple search form on my page /. class SearchForm(Form): query = CharField(max_length=256, label="Search", required=False, widget=TextInput(attrs={'placeholder': 'Search …', 'class': 'form-control'})) page = IntegerField(min_value=8, initial=1, widget=HiddenInput()) sort = CharField(max_length=16, initial="id", widget=HiddenInput()) order = CharField(max_length=4, initial="asc", widget=HiddenInput()) My (simplified) view is this: def search(request): search_form = SearchForm(request.GET) return render(request, "search.html", {'search_form': search_form}) My goal is to have search_form.cleaned_data['<FIELD>'] return the initial values I set in the class SearchForm, without having to check wether they are exist None or are empty ''. Unfortunately my code does not work as the input elements are renderd like this: <input id="id_page" name="page" type="hidden" /> <input id="id_sort" maxlength="16" name="sort" type="hidden" /> <input id="id_order" maxlength="4" name="order" type="hidden" /> Any ideas? -
Create new entry or update field of existing entry in Django Model
I have a model with following structure : class TestModel(models.Model): field1 = models.IntegerField() field2 = models.IntegerField() is_valid = models.BooleanField(default=True) class Meta: unique_together = ('field1', 'field2',) Now suppose I have a data set like this in my DB- field1 field2 is_valid 1 "a" true 1 "b" true 1 "c" true 2 "y" true 2 "z" true I will be receiving new data according to my field1 values. Say I receive a data set {a, f, g, h} where field1 is equal to 1. Now what I am trying to achieve is that if there is a field2 value in my data set which is not already present in the database, for a given field1 value, then insert those values. Like - {f, g, h} should get inserted in the database, as a is already present. Also value of is_valid field for all those values apart from the values in the given data set should become false ,i.e, is_valid for - b, c will become false. Final values in database should look like - field1 field2 is_valid 1 "a" true 1 "b" false 1 "c" false 1 "f" true 1 "g" true 1 "h" true 2 "y" true 2 "z" true It … -
How do you override bootstrap.min.css? Django
On my page I have a toolbar which is supposed to be centered in the middle. I have a seperate css sheet which centres it, however it keeps being overriden by the min.css file. In my body content.css I have: .btn-toolbar .btn, .btn-toolbar .btn-group, .btn-toolbar .input-group { float:none !important; } But when I inspect the page via the console it it always shows this in the min.css: .btn-toolbar .btn, .btn-toolbar .btn-group, .btn-toolbar .input-group { float:left; } How do I override it? -
apache + django +wsgi_mod server, can't startup application from client server
When the Django application in development mode, I can start the application in server through the WEB page, but I can't startup application through the WEB page after deploying the django application by Apache, I found the application process loaded, but the application cannot pop-up interface. I create process startup the application by follow code: commond = ur"pybot.bat D:\Test\pagePerformance\1-testCase\pagePerformance-ie.txt" msgtmp = sub.Popen(commond,stdout=sub.PIPE,stderr=sub.PIPE) Any idea to solve this problem? sorry for my badly english! -
highchart is not displaying in django twitter bootstrap
I am having problem with displaying highchart in django. I am using twitter bootstrap.Chart is not showing in chart.html. Can anyone help me what I am doing wrong here?Please find below version of django Django==1.8.7 django-highcharts==0.1.7 base.html: <!DOCTYPE html> {% load staticfiles %} <html> <head> {% block title %}<title>mbr page </title>{% endblock %} <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="{% static "mbr/css/boostrap-fluid-adj.css" %}" rel="stylesheet"> <link href="{% static "mbr/css/bootstrap.min.css" %}" rel="stylesheet" media="screen"> <link href="{% static "mbr/css/bootstrap-responsive.css" %}" rel="stylesheet"> <style> body { padding-top: 50px; } @media (max-width: 980px) { body { padding-top: 0; } } </style> </head <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container-fluid"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div class="nav-collapse collapse"> <ul class="nav pull-right"> <li><a href="/admin/">Login</a></li> </ul> <ul class="nav navbar-nav"> <li class="active"><a href="/mbr/">Home</a></li> <li><a href="{% url 'search_form' %}">Search s</a></li> <li><a href="{% url 'results_list' %}">Results History</a></li> <li><a href="{% url 'chart_test' %}">Statistics</a></li> </ul> </div> </div> </div> </div> <div class="container-fluid"> <div class="row-fluid"> <div class="span3"> <div class="well sidebar-nav"> <h3> Name</h3> <p class="active"><a href="/mbr/4/">TEST1</a></p> <p><a href="/mbr/3/">TEST2</a></p> <p><a href="/mbr/2/">TEST3</a></p> <p><a href="/mbr/1/">TEST4</a></p> </div> </div> <div class="span9"> {% block content %} {% endblock %} </div> </div> </div> <hr> <script src="{% static 'mbr/js/jquery-3.2.0.js' %}"></script> <script src="{% static 'mbr/js/bootstrap.min.js' %}"></script> </body> </html> … -
Applying ratelimit decorator to auth views.py
I want to rate limit several views in my Django app (login, register_account, password reset, ...). I am already using Django-Ratelimit. But I am unsure how to add this decorator to existing views. Writing my own views and using them in a custom urls.py looks like a lot of boilerplate code just to add some decorators. -
How to mount django app at root of site on Apache?
I'm following the documentation here: https://modwsgi.readthedocs.io/en/develop/user-guides/quick-configuration-guide.html I'm using apache2 on Debian I change the settings by editing apache2.conf When I mount my app like this, WSGIScriptAlias /app /path/to/mysite and it works when I browse 127.0.0.1/app/. However, when I try to mount my app at root like this: WSGIScriptAlias / /path/to/mysite and I browse 127.0.0.1/ , the default page "It works!" is shown by apache The option DocumentRoot /path/to/mysite in apache2.conf doesn't work, too. -
Django 10.6 throws 'mbcs' error in autoload.py when trying to run server on Windows 10
I am trying to get started with Django and installed the 10.6 version through pip on my Windows 10 machine. Following the tutorial on its main website, I started a new project called "mysite" and tried to run "python manage.py runserver" but it gives me following error: (C:\Users\User\Anaconda3) C:\mysite>python manage.py runserver Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 58, in execute super(Command, self).execute(*args, **options) File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 97, in handle self.run(**options) File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 106, in run autoreload.main(self.inner_run, None, options) File "C:\Users\User\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 333, in main reloader(wrapped_main_func, args, kwargs) File "C:\Users\User\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 304, in python_reloader exit_code = restart_with_reloader() File "C:\Users\User\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 290, in restart_with_reloader exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ) UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: invalid character Does anyone have experience with this and know an answer? I suspect that it is the %-sign in python 3.5 because putting "%matplotlib inline" in a python file throws an error, too. Unfortunately, I am not that familiar with … -
Return django validation errors in JSON format
Suppose I am building a registration/signup or any form in general for my web app in Django and I want the same form for Web/Android/IOS. So I want the frontend and backend(Django) to communicate via JSON. My question is how can I send validation errors in JSON format if the user on any platform(Web/Android/IOS) gives me invalid data like "the email already exists" type of errors? I need the best way possible to handle this type of scenarios and well-detailed example/explanation will be much appreciated. Thank You. -
how to create an invoice in pdf with carcode in django
i want to create an invoice in pdf format with barcode, first mybarcode.py file to create barcode using reportlab # mybarcode.py file to create barecode from reportlab.lib.units import mm from reportlab.graphics.barcode import createBarcodeDrawing from reportlab.graphics.shapes import Drawing, String from reportlab.graphics.charts.barcharts import HorizontalBarChart class MyBarcodeDrawing(Drawing): def __init__(self, text_value, *args, **kw): barcode = createBarcodeDrawing('Code128', value=text_value, barHeight=19*mm, humanReadable=True) Drawing.__init__(self,barcode.width,barcode.height,*args,**kw) self.add(barcode, name='barcode') views function to generate pdf with barcode. # views.py from reportlab.platypus import SimpleDocTemplate from reportlab.platypus.tables import Table cm = 2.54 def print_pdf(request): import mybarcode product = Product.objects.get(id = id) d = mybarcode.MyBarcodeDrawing(product.code) binaryStuff = d.asString('jpg') response = HttpResponse(content_type='application/pdf') filename=somefilename.pdf' elements = [] doc = SimpleDocTemplate(response, rightMargin=0, leftMargin=6.5 * cm, topMargin=0.3 * cm, bottomMargin=0) data=[("barcode", binaryStuff),("name", "some_name")] table = Table(data) elements.append(table) doc.build(elements) return response and getting this error : 'utf8' codec can't decode byte 0xff in position 0: invalid start byte -
Open pdf file with Django
I'm trying to merge two pdf files in Django with PyPDF2 and ReportLab. My view is as follows: @login_required def export_to_pdf(request, user_id): member = Member.objects.filter(user_id=user_id).values('user_id', 'user__first_name', 'user__last_name', 'company_name', 'vat_number', 'address', 'postcode', 'city', 'user__email', 'telephone', 'subscription__type__name', 'subscription__type__limit', ).annotate(num_calculations=Count('user__calculations'))[0] company_address = "{}, {} {}".format(member['address'], member['postcode'], member['city']) buffer = BytesIO() # Create the PDF object, using the BytesIO object as its "file." p = canvas.Canvas(buffer, pagesize=A4) p.setFont('Helvetica-Bold', 8) p.drawString(70, 765, "{}".format(member['company_name'])) p.drawString(70, 731, "{}".format(company_address)) p.drawString(70, 714, "{}".format(member['telephone'])) p.drawString(335, 697, "{}".format(member['vat_number'])) p.drawString(335, 697, "{}".format(member['vat_number'])) p.save() buffer.seek(0) new_pdf = PdfFileReader(buffer) existing_pdf = PdfFileReader(open('master/files/file.pdf', "rb")) page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) output = PdfFileWriter() output.addPage(page) output_stream = open("master/files/new_file.pdf", "wb") output.write(output_stream) output_stream.close() with open('master/files/new_file.pdf', 'r', encoding="Latin-1") as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=some_file.pdf' return response The project tree is as follows : Thus, I create new file and then I open an existing file file.pdf, and then I merge those two files. At the end I create a file for output new_file.pdf. That works fine, but the problem is with the file which is returned. If I run export_to_pdf function I should get new_file.pdf. I get that file, but the content of that file is only what I created with p = canvas.Canvas(buffer, pagesize=A4) p.setFont('Helvetica-Bold', 8) … -
Django CMS per-site cache not working for CMS pages
I'm trying to setup Django's per-site cache (https://docs.djangoproject.com/en/1.10/topics/cache/#the-per-site-cache) with Django CMS and I can't get the cache to work for the CMS pages, however it works for apphooked pages. This is a snippet of my settings: MIDDLEWARE_CLASSES = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.gzip.GZipMiddleware', 'htmlmin.middleware.HtmlMinifyMiddleware', 'htmlmin.middleware.MarkRequestMiddleware', 'cms.middleware.utils.ApphookReloadMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.redirects.middleware.RedirectFallbackMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ] CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_SECONDS = 60 CACHE_MIDDLEWARE_KEY_PREFIX = 'mysite-' CMS_PAGE_CACHE = True CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'cache_table', 'TIMEOUT' : 60*60*24, 'OPTIONS': { 'MAX_ENTRIES': 10000, } } } If I navigate to an apphooked page, the response header is: Cache-Control: max-age=60 Which is correct. However with a CMS page I get the header: Cache-Control: max-age=0, no-store, no-cache, must-revalidate Which is incorrect. The Django CMS documentation (http://docs.django-cms.org/en/release-3.4.x/how_to/caching.html) says that the UpdateCacheMiddleware should be first FetchFromCacheMiddleware last, which is what I've done and have no luck. I've restarted the server, tried updating content on the page and re-publishing but still having no luck. What am I missing here?! Any help would be much appreciated. -
how to create serializer for an enum field in django rest framework
i am writing an API in python django rest framework and i am stuck at creating a serializer field for an ENUM, how can i create a serializer field for an ENUM field. my model code is: class Queue(models.Model): class Meta: db_table = 'queues' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=45) type = EnumChoiceField(QueueTypes, default=QueueTypes.pending) date = models.DateTimeField(auto_now=True) and i am writing a serializer for this model. class QueueSerializer(serializers.ModelSerializer): class Meta: model = Queue fields = ('__all__') id = serializers.CharField(read_only=True) name = serializers.CharField(max_length=45, required=True) type=?????# what am i supposed to do here? date = serializers.DateTimeField(read_only=True) -
Django - Saving formset data with differetn values
I have such models: class House(models.Model): name = models.CharField(max_length=50, blank=True, null=True) def __unicode__(self): return '%s' % self.name class Rooms(models.Model): house = models.ForeignKey(House, null=True) room = models.CharField(max_length=50, blank=True, null=True) people = models.IntegerField(blank=True, null=True) def __unicode__(self): return '%s' % self.room class People(models.Model): room = models.ForeignKey(Rooms, null=True) name = models.CharField(max_length=30) surname = models.CharField(max_length=50) def __unicode__(self): return '%s' % self.surname So if in the house there are two rooms with two people in each room i need to save two People instances with one room key and the second with other room key instead of this my code saves four People instances in each Rooms. My code looks like this: for people in people_formset: name = adult_tourists.cleaned_data['name'] surname = adult_tourists.cleaned_data['surname'] for room in house.rooms_set.all(): for people in range(room.people): p = People.objects.create(room=room, name=name, surname=surname) p.save() Thanks for help -
Django dropped table still exists
Having problems with a model in one of my django apps. I can make an instance of the model, but when I go to access it, I get a message saying the table does not exist. I'm using Django 1.95 and I tried to refresh the db by following the suggestions from this answer: http://stackoverflow.com/a/36565161/2516846 But it does not remove the model, so when I run migrate again, it says the relation already exists, even though I have dropped it's table using dbshell. Summary: Cannot create model again as relation already exists, yet cannot access model in my app as it says table doesn't exist Is there a reference to this table/model stored else where which I need to remove? -
Mocking open function with mock_open
So I have function in my Django app business logic I want to test: def parse_sectors_from_csv(): sectors_csv = open(os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv')) sectors_csv_reader = csv.DictReader(sectors_csv) return [ { 'model': 'sector.sector', 'id': index, 'fields': { 'name': row.get('Sector'), 'slug': slugify(row['Sector']), 'type_id': row.get('Type_Id') } } for index, row in enumerate(sectors_csv_reader, 1) ] I already test it for file existence and for existence of heading row. Now I want to mock open(os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv')) In my test.py I wrote with patch('__builtin__.open', mock_open(read_data=sectors_csv_mock), create=True) as m: sectors = service.parse_sectors_from_csv() print('Sectors:', sectors) self.assertEqual(expected_sectors, sectors) But as I understand, it's passes empty file to function as it prints Sectors: [] I read mock_open dock for a few times and still can't figure it out. >>> with patch('__main__.open', mock_open(read_data='bibble')) as m: ... with open('foo') as h: # what's happening here? ... result = h.read() # here? ... >>> m.assert_called_once_with('foo') # and here? >>> assert result == 'bibble' -
Django create new instance of model with '__init__' function from table, instance data is error?
there is my model code which have problem: class Person(models.Model): name = models.CharField(max_length=20) url = models.URLField() card_id = models.CharField(max_length=20) def __init__(self, name, card_id, url, *args, **kwargs): super().__init__(*args, **kwargs) self.name = name self.card_id = card_id self.url = url def __str__(self): return str({ 'name': self.name, 'card_id': self.card_id, 'url': self.url }) there is test code: class PersonTestCase(TestCase): def setUp(self): Person.objects.create(name="test", card_id="123", url="http://www.baidu.com") def test_get(self): p = Person.objects.get(name="test") print(p) the print of test function 'test_get' is: {'name': 1, 'card_id': 'test', 'url': '123'} which is error. the value of name is data of id column in table , the value of card_id is data of name column in table, ... but if I change function __init__ to follow: def __init__(self, id=None, name=None, card_id=None, url=None, *args, **kwargs): or delete function __init__, got the print of function test_get is: {'name': 'test', 'card_id': '123', 'url': 'http://www.baidu.com'} which is right. So what is best way to create new instance from table data? -
problema with django user
I have some problems with Django users The first: I create a new user, I do like this: user = User.objects.create_user(username='douglas2', password='password') user.save() users = User.objects.all() users the output: < QuerySet [< User: douglas >, < User: douglas2 >] > but when I try to log in Django it accuses invalid user or password...what I doing wrong? The second problem is: When I'm on the evaluation page, the option of evaluator allow me to select any evaluator, what was not to be...how, to correct this I have to do this page start from the administration page(http://127.0.0.1:8000/admind/evaluation)? The third problem: I made with that attribute(appraiser) of model "Evaluation" be unique, because the appraiser can evaluate the candidate just once.But when I select the second appraiser (in the wrong field that I quoted above)Django said that this appraiser already evaluate this candidate, even not... I put more than one doubt on the same question because I believe that in this case, these problems are all related My codes: **views.py** from django.shortcuts import render, get_object_or_404 from .models import Candidate, Criterion, Evaluation from django import forms from .forms import CandForm from .forms import EvalForm from django.shortcuts import redirect from django.db import IntegrityError def canditate_list(request): … -
Show field_dict.items() of django-reversion in template
I am tring to use django reversion app in my project. I am little bit comfused. How to show list of changes (field_dict.items()) in template? models.py: @reversion.register() class Function(models.Model): ***FIELDS*** views.py: def function_revisions(request, function_code): function = get_object_or_404(Function, pk=function_code) versions = Version.objects.get_for_object(Function) context = { 'function': function, 'versions': versions, } return render(request, 'project/function_revisions.html', context) function_revisions.html: {% for version in versions %} <p>Version: {{ forloop.counter }}.</p> <p>Revision by {{ version.revision.user }}.</p> <p>Date of revision : {{ version.revision.date_created }}.</p> {% for field_name, field_value in version.field_dict.items() %} <-- ??? <p>Field </p>{{ field_name }} had the value {{ field_value }}<p> {% endfor %} {% endfor %}